2013-03-07 47 views
2

我有以下GGPLOT2情节:转换箱图来密度在GGPLOT2中的R

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数据集中,我想为每个制造商制作一个密度图,绘制每个cyl值的分布图displ。 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 ~ .) 

但我不想不同网格,我想他们是在像直方图情况下,同样的情节不同的条目。

+0

我已经展示了我能想到的两种方式(您已经排除了其中之一 - 切面)。看看对方是否有帮助。如果不是,对不起,我无法帮助。 – Arun 2013-03-07 15:28:38

回答

5

这样的事情?对于histogramdensity图,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) 

给出:

enter image description here

编辑:因为,你不想facetting,我能想到的唯一的另一种方式是通过粘贴manufacturercyl创建一个单独的组在一起:

dd <- mpg 
dd$grp <- factor(paste(dd$manufacturer, dd$cyl)) 

ggplot(dd, aes(x=displ)) + 
    geom_density(aes(fill=grp), position="identity") 

给出:

enter image description here

+0

我的例子并不清楚我正在修改它 – user248237dfsf 2013-03-07 15:12:27

+0

你的代码对我有帮助,但它只是有另一个变量,增加了“虹膜”没有说明的复杂性,所以这是一个坏例子 – user248237dfsf 2013-03-07 15:17:07

+0

如果我只能考虑* *对于直方图和密度图,y变量都是count **。谢谢 – 2017-11-05 22:19:30