barplot with 3 variables (continous X and Y and third stacked variable)

孤人 提交于 2019-12-09 13:58:22

问题


I have some data like this:

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

I want to plot size on the y-axis and other two variables zero_co and non-zero CO as a stacked bars on the x-axis. I am trying to plot this using gplots and ggplots but finding difficulties. How do I plot this?


回答1:


Here is a solution if I understand it correctly. As you have quantative variable at both x and y axis you can not do with bar plot. You need to use rectangle (look like bar anyway).

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()

Give you the plot:




回答2:


Here is where I could get to based on my limited understanding:

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)




回答3:


I'm not sure how you wish the final plot to look like but here's a ggplot2 proposal.

First, reshape the data into the long format:

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

Calculate absolute value (I suppose value represents the percentage of size.):

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

Plot:

library(ggplot2)    

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



来源:https://stackoverflow.com/questions/14215263/barplot-with-3-variables-continous-x-and-y-and-third-stacked-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!