GGplot 具有不同颜色的堆叠条形图
GGplot Stacked Barplot with individual colors
我想创建一个堆叠条形图,其中每列的底部类别为绿色,每列的上部类别从深红色变为亮红色(从左到右)。
例如,使用此代码:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
library(plyr)
# Sort by dose and supp
df_sorted <- arrange(df2, dose, supp)
df_cumsum <- ddply(df_sorted, "dose",
transform, label_ypos=cumsum(len))
ggplot(data=df_cumsum, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity")+
geom_text(aes(y=label_ypos, label=len), vjust=1.6,
color="white", size=3.5)+
scale_fill_manual(values = c("red", "green")) +
theme_minimal()
可以吗?
如果您想为顶部的条形图添加不同的颜色,您需要为它们创建不同的因子。例如,通过为 OJ
值粘贴 supp
和 dose
列:
df_cumsum$supp <- as.character(df_cumsum$supp)
df_cumsum$supp <- ifelse(df_cumsum$supp == "OJ", paste(df_cumsum$supp, df_cumsum$dose, sep = ""), df_cumsum$supp)
df_cumsum$supp <- as.factor(df_cumsum$supp)
ggplot(data=df_cumsum, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity")+
geom_text(aes(y=label_ypos, label=len), vjust=1.6,
color="white", size=3.5)+
scale_fill_manual(values = c("#E74C3C", "#EC7063", "#F1948A", "#27AE60")) +
theme_minimal()
我想创建一个堆叠条形图,其中每列的底部类别为绿色,每列的上部类别从深红色变为亮红色(从左到右)。
例如,使用此代码:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
library(plyr)
# Sort by dose and supp
df_sorted <- arrange(df2, dose, supp)
df_cumsum <- ddply(df_sorted, "dose",
transform, label_ypos=cumsum(len))
ggplot(data=df_cumsum, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity")+
geom_text(aes(y=label_ypos, label=len), vjust=1.6,
color="white", size=3.5)+
scale_fill_manual(values = c("red", "green")) +
theme_minimal()
可以吗?
如果您想为顶部的条形图添加不同的颜色,您需要为它们创建不同的因子。例如,通过为 OJ
值粘贴 supp
和 dose
列:
df_cumsum$supp <- as.character(df_cumsum$supp)
df_cumsum$supp <- ifelse(df_cumsum$supp == "OJ", paste(df_cumsum$supp, df_cumsum$dose, sep = ""), df_cumsum$supp)
df_cumsum$supp <- as.factor(df_cumsum$supp)
ggplot(data=df_cumsum, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity")+
geom_text(aes(y=label_ypos, label=len), vjust=1.6,
color="white", size=3.5)+
scale_fill_manual(values = c("#E74C3C", "#EC7063", "#F1948A", "#27AE60")) +
theme_minimal()