我有一个数据集区域如下。
Region Color 0-25 25-50 50-75 75-100
AF Green 51% 14% 24% 11%
AP Red 5% 12% 9% 74%
EU Yellow 18% 3% 36% 43%
Global Green 34% 11% 19% 36%
LA Green 44% 23% 22% 11%
NA Green 100% 0% 0% 0%
我想使用ggplot为上述数据集绘制堆积条形图。
我正在寻找:,比如绘制全局数据时,我希望颜色为绿色,范围为0-25
,深绿色为25-50
,浅灰色为50-75
,黑暗75-100
之间的灰色。
Simmilary为其他人,红色,深红色,浅灰色和深灰色为AP区域。
类似的东西:this post
任何关于此的提示都会有很大帮助。感谢..
答案 0 :(得分:0)
这是一种使用绿色的方法。
dput(df)
structure(list(Region = structure(c(1L, 2L, 3L, 4L, 5L, NA), .Label = c("AF",
"AP", "EU", "Global", "LA", "Region"), class = "factor"), Color = structure(c(2L,
3L, 4L, 2L, 2L, 2L), .Label = c("Color", "Green", "Red", "Yellow"
), class = "factor"), `0-25` = c(51, 5, 18, 34, 44, 100), `26-50` = c(14,
12, 3, 11, 23, 0), `51-75` = c(24, 9, 36, 19, 22, 0), `76-100` = c(11,
74, 43, 36, 11, 0)), .Names = c("Region", "Color", "0-25", "26-50",
"51-75", "76-100"), row.names = 2:7, class = "data.frame")
然后,melt
作为tidyr
,cut
创建了颜色因素。
df.m <- melt(df, id.vars = "Region", measure.vars = 3:6)
df.m$color.bin <- cut(x = df.m$value, breaks = c(0, 26, 51, 76, 100))
df.m$color.bin <- as.factor(df.m$color.bin)
评论后编辑
然后我为ggplot添加了一个因子变量来使用。
df.m$shade <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "p","p","p","p","p","p","p","p")
最后一步是首次使用ggplot和堆叠,并手动设置填充颜色。虽然有六个区域,但我只为前四个匹配你的配色方案。你可以完成剩下的工作。我添加了color
参数来显示堆叠段之间的划分。我添加了guides
调用来消除字母和颜色的长篇传说:
ggplot(df.m, aes(x = Region, y = value, fill = shade)) +
geom_bar(stat = "identity", position = "stack", color = "black") +
scale_fill_manual(values = c("forestgreen", "lightcoral", "lemonchiffon", "blue", "grey30", "grey30",
"lightgreen", "lightcoral", "lemonchiffon", "lightblue", "grey30", "grey30",
"lightgreen","lightcoral", "yellow", "lightblue", "grey30", "grey30",
"lightgreen", "grey70","yellow", "blue", "grey30", "grey30")) +
guides(fill = FALSE)