Cluster stacked bargraph

倾然丶 夕夏残阳落幕 提交于 2019-12-11 19:38:50

问题


I want to plot something like this in R.

I found some similar solution here so I tried something similar:

test  <- data.frame(person=c("group 1", "group 2", "group 3"), 
                value1=c(100,150,120),  # male   
                value2=c(25,30,45) ,    # female
                value3=c(25,30,45),     # male
                value4=c(100,120,150),  # female
                value5=c(10,12,15),     # male
                value6=c(50,40,70))     # female

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1' | melted$variable == 'value2',]$cat <- "sub group 1"
melted[melted$variable == 'value3' | melted$variable == 'value4',]$cat <- "sub group 2"
melted[melted$variable == 'value5' | melted$variable == 'value6',]$cat <- "sub graoup 3"

p = ggplot(melted, aes(x = cat, y = value, fill = variable)) 
    + geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ person)

What I ended with is:

The problem is now I have 6 different values with 6 different colors. What I really want is 2 different values, let's call theme male and female represented by 2 different colors.

How can I do it in R? The data can be constructed in any different way (doesn't have to use data.frame as above). I don't need to use ggplot. In fact, I prefer the white clean background in example image than the grey background I got using ggplot.


回答1:


You could just add another variable to your melted data frame holding the gender information and then plot in ggplot. The background can also be easily changed to white. I edited your code example and posted it below.

I hope this helps!

test  <- data.frame(person=c("group 1", "group 2", "group 3"), 
                value1=c(100,150,120),  # male   
                value2=c(25,30,45) ,    # female
                value3=c(25,30,45),     # male
                value4=c(100,120,150),  # female
                value5=c(10,12,15),     # male
                value6=c(50,40,70))     # female

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1' | melted$variable == 'value2',]$cat <- "sub group 1"
melted[melted$variable == 'value3' | melted$variable == 'value4',]$cat <- "sub group 2"
melted[melted$variable == 'value5' | melted$variable == 'value6',]$cat <- "sub group 3"
melted$gender <- ''
melted[melted$variable %in% sprintf("value%i",c(1,3,5)),]$gender <- "female"
melted[melted$variable %in% sprintf("value%i",c(2,4,6)),]$gender <- "male"


p = ggplot(melted, aes(x = cat, y = value, fill = gender)) 

p + geom_bar(stat = 'identity', position = 'stack') +   facet_grid(~ person) + 
scale_fill_manual(values = c("orangered","dodgerblue2")) + 
theme(panel.background = element_rect(fill = 'white'))


来源:https://stackoverflow.com/questions/33434974/cluster-stacked-bargraph

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