Show/Hide Code
library(tidyverse)
ggplot(iris, aes(x = Sepal.Length)) +
geom_density(fill="#69b3a2", alpha=0.8) # 可选主题 theme_ipsum()
核密度曲线图其实是一个平滑的直方图,曲线下面积是1。
通过geom_density()
函数可以绘制核密度曲线图。
library(tidyverse)
ggplot(iris, aes(x = Sepal.Length)) +
geom_density(fill="#69b3a2", alpha=0.8) # 可选主题 theme_ipsum()
镜像密度曲线图见 Section 2.1.2
ggplot(iris, aes(x = Sepal.Length, fill = Species), ) +
geom_density(alpha=0.8)
ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha=0.8) +
facet_wrap(~ Species) +
theme(legend.position = "none")
分面不如山脊图好看,见 Chapter 5
通过position=“fill”绘制堆叠密度图,可以看到每个组的比例
library(hrbrthemes) # theme_ipsum
ggplot(data=diamonds, aes(x=price, group=cut, fill=cut)) +
geom_density(adjust=1.5, position="fill") +
theme_ipsum()
还可以使用annot数据框来添加注释,下面的例子中,我们在鸢尾花的密度曲线上添加了每个物种的名称注释。
<- data.frame(
annot Species = c("setosa", "versicolor", "virginica"),
x = c(5.2, 5.5, 6.4),
y = c(1.2, 0.8, 0.8)
)
ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha=0.8) +
geom_text(data=annot, aes(x=x, y=y, label=Species, color=Species), hjust=0, size=4.5) +
theme_ipsum() + # 适合印刷的主题
theme(legend.position = "none")
library(geomtextpath)
library(hrbrthemes)
ggplot(iris, aes(x = Sepal.Length, color = Species, label = Species)) +
geom_textdensity() +
theme_bw() +
theme(legend.position = "none")
library(geomtextpath)
library(hrbrthemes)
ggplot(iris, aes(x = Sepal.Length, color = Species, label = Species)) +
geom_textdensity(vjust = -0.4, hjust = "ymid") + # hjust = "ymid" 调整标签位置
theme_bw() +
theme(legend.position = "none")
text参数:
r-graph-gallery 还有一些示例: geomtextpath