[英]converting boxplots to densities in ggplot2 in R
我有以下ggplot2图:
ggplot(iris) + geom_boxplot(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip()
我想将其绘制为水平密度图或直方图,这意味着每个物种都有密度线图或直方图,而不是箱线图。 这并不能解决问题:
> ggplot(iris) + geom_density(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip()
Error in eval(expr, envir, enclos) : object 'y' not found
为简单起见,我将Species
用作x
变量和fill
但在我的实际数据中,X轴表示一组条件,而填充表示另一组条件。 虽然这对于绘图目的不重要。 我正在尝试使它成为X轴代表不同的条件,在这些条件下y
值绘制为密度/直方图而不是盒图。
编辑该变量可以更好地说明,该变量具有两个类似于类的因子变量。 在mpg
数据集,我想为每个制造商的密度阴谋,阴谋的分布displ
为每个cyl
的价值。 x轴(在翻转坐标中是垂直的)代表每个制造商,直方图的值是displ
,但是对于每个制造商,我想要的直方图与该制造商的cyl
值一样多。 希望这更清楚。 我知道这行不通,因为y=
期望计数。
ggplot(mpg, aes(x=manufacturer, fill=cyl, y=displ)) +
geom_density(position="identity") + coord_flip()
我得到的最接近的是:
> ggplot(mpg, aes(x=displ, fill=cyl)) +
+ geom_density(position="identity") + facet_grid(manufacturer ~ .)
但是我不想使用不同的网格,我希望它们在同一图中的不同条目像直方图一样。
像这样吗 对于histogram
和density
图, y
变量均为count
。 因此,您必须绘制x = Petal.Length
其频率(对于给定的binwidth)将在y轴上绘制。 只需使用fill=Species
和x=Petal.Length
即可通过Species
赋予颜色。
对于histogram
:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_histogram(position="identity") + coord_flip()
对于density
:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_density(position="identity") + coord_flip()
编辑:也许您正在寻找facetting
?
ggplot(mpg, aes(x=displ, fill=factor(cyl))) +
geom_density(position="identity") +
facet_wrap( ~ manufacturer, ncol=3)
得到:
编辑:因为您不希望facetting
,所以我想到的唯一另一种方法是通过将manufacturer
和cyl
粘贴在一起来创建单独的组:
dd <- mpg
dd$grp <- factor(paste(dd$manufacturer, dd$cyl))
ggplot(dd, aes(x=displ)) +
geom_density(aes(fill=grp), position="identity")
得到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.