我有以下ggplot2图:
ggplot(iris) + geom_boxplot(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip()
Run Code Online (Sandbox Code Playgroud)
我想将其绘制为水平密度图或直方图,意味着每个物种或直方图的密度线图而不是箱形图.这不是诀窍:
> ggplot(iris) + geom_density(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip()
Error in eval(expr, envir, enclos) : object 'y' not found
Run Code Online (Sandbox Code Playgroud)
为简单起见,我使用Species
的x
变量并作为fill
但在我的实际数据中的X轴表示一组条件和填充表示另一个.虽然这对绘图目的无关紧要.我试图这样做,所以X轴代表不同的条件,其值y
被绘制为密度/直方图而不是箱形图.
使用具有两个类似因子的变量(如Species)的变量可以更好地说明编辑.在mpg
数据集中,我想为每个制造商制作密度图,绘制displ
每个cyl
值的分布.x轴(在翻转坐标中是垂直的)代表每个制造商,并且直方图的值是displ
,但是对于每个制造商,我想要与cyl
该制造商的值一样多的直方图.希望这更清楚.我知道这不起作用因为y=
预期会很重要.
ggplot(mpg, aes(x=manufacturer, fill=cyl, y=displ)) +
geom_density(position="identity") + coord_flip()
Run Code Online (Sandbox Code Playgroud)
我得到的最近的是:
> ggplot(mpg, aes(x=displ, fill=cyl)) +
+ geom_density(position="identity") + facet_grid(manufacturer ~ .)
Run Code Online (Sandbox Code Playgroud)
但我不想要不同的网格,我希望它们在直方图的情况下是同一个图中的不同条目.
像这样的东西?对于两者histogram
和density
图,y
变量是count
.因此,您需要绘制x = Petal.Length
其频率(针对给定的宽度)将在y轴上绘制的情节.只需用fill=Species
它x=Petal.Length
来提供颜色Species
.
用于histogram
:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_histogram(position="identity") + coord_flip()
Run Code Online (Sandbox Code Playgroud)
用于density
:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_density(position="identity") + coord_flip()
Run Code Online (Sandbox Code Playgroud)
编辑:也许你在找facetting
?
ggplot(mpg, aes(x=displ, fill=factor(cyl))) +
geom_density(position="identity") +
facet_wrap( ~ manufacturer, ncol=3)
Run Code Online (Sandbox Code Playgroud)
得到:
编辑:因为,你不想要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")
Run Code Online (Sandbox Code Playgroud)
得到:
归档时间: |
|
查看次数: |
1754 次 |
最近记录: |