我想在R中绘制类似的内容。
我找到了一些类似的解决方案here所以我尝试了类似的东西:
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)
我结束的是:
问题是现在我有6种不同的颜色,有6种不同的颜色。我真正想要的是2个不同的值,让我们用2种不同的颜色来表示主题male
和female
。
我怎样才能在R中做到?数据可以以任何不同的方式构建(不必如上所述使用data.frame)。我不需要使用ggplot
。事实上,我更喜欢示例图像中的白色干净背景而不是我使用ggplot获得的灰色背景。
答案 0 :(得分:0)
您可以将另一个变量添加到包含性别信息的融化数据框中,然后在ggplot中绘图。背景也可以很容易地变成白色。我编辑了您的代码示例并将其发布在下面。
我希望这有帮助!
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'))