2013-01-08 39 views
0

我有這樣一些數據:barplot與3個變量(連X和Y和第三堆疊變量)

myd <- structure(list(var1 = structure(1:4, .Label = c("II", "III", 
     "IV", "V"), class = "factor"), zero_co = c(15.15152, 3.030303, 
     0, 0), non_zero_CO = c(84.84848, 96.969697, 100, 100), size = c(230, 
     813, 317, 1532)), .Names = c("var1", "zero_co", "non_zero_CO", 
     "size"), row.names = c(NA, -4L), class = "data.frame") 

# myd 
# I     II   III IV  V 
# zero_co  15.15152 3.030303 0  0 
# non-zero CO 84.84848 96.969697 100 100 
# size   230.00000 813.000000 317 1532 

我想在y軸和其它兩個變量zero_conon-zero CO作爲繪製size在x軸上的堆疊酒吧。我正在嘗試使用gplotsggplots來繪製此圖,但發現有困難。我如何繪製這個?

+2

你的數據是絕對無法讀取。學習如何在R中創建可重複的示例:http://stackoverflow.com/q/5963269/684229 – TMS

+0

對不起。我現在編輯它。 – PoisonAlien

+0

你能證明你做了什麼嗎? – SHRram

回答

4

這是一個解決方案,如果我理解正確。由於您在x軸和y軸都有定量變量,因此無法使用條形圖。你需要使用矩形(無論如何看起來像吧)。

myd <- data.frame (var1 = c("II", "III", "IV", "V"), zero_co = c(15.15152 , 3.030303, 0,  0), 
      non_zero_CO = c(84.84848, 96.969697, 100, 100), 
       size = c(230.00000, 813.000000, 317, 1532)) 

    require(ggplot2) 

ggplot(myd) + geom_rect(aes(xmin = 0, xmax = zero_co, ymin =size , ymax =size + 80), fill = "lightgreen") + 
geom_rect(aes(xmin = zero_co, xmax = zero_co + non_zero_CO, ymin =size , ymax =size + 80), fill = "darkblue") + theme_bw() 

給你的情節:

enter image description here

+0

@poison Alien你能確定這是不是你要找的? – jon

+0

嗨jon - 謝謝各位的答案。這就是我一直在尋找的! – PoisonAlien

3

這裏就是我能得到根據我有限的瞭解:

myd <- data.frame (var1 = c("II", "III", "IV", "V"), zero_co = c(15.15152 , 3.030303, 0,  0), 
      non_zero_CO = c(84.84848, 96.969697, 100, 100), 
       size = c(230.00000, 813.000000, 317, 1532)) 
myd1 <- as.matrix (t(myd[,2:3])) 

barplot(myd1) 

enter image description here

1

我不知道你怎麼想的最後情節看似但這裏有一個ggplot2建議。

首先,數據重塑爲長格式:

library(reshape2) 
myd_long <- melt(myd, measure.vars = c("zero_co", "non_zero_CO")) 

計算絕對值(我想value代表的size百分比):

myd_long <- within(myd_long, valueAbs <- size * value/100) 

簡介:

library(ggplot2)  

ggplot(myd_long, aes(y = valueAbs, x = var1, fill = variable)) + 
    geom_bar(stat = "identity") 

enter image description here