2013-03-07 63 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