带有3个变量的条形图(连续的X和Y以及第三个堆叠变量)

时间:2013-01-08 12:46:03

标签: r plot ggplot2 visualization

我有一些这样的数据:

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轴上绘制size,在x轴上绘制其他两个变量zero_conon-zero CO作为堆叠条。我试图使用gplotsggplots绘制此图,但发现有困难。我该如何策划?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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