brunosm
brunosm

Reputation: 166

GGplot Stacked Barplot with individual colors

I want to create a stacked barplot where the bottom category of each column is green and the upper category of each column goes from dark red to bright red (from left to right).

For example, using this code:


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




Is it possible?

Upvotes: 0

Views: 196

Answers (1)

Sven
Sven

Reputation: 1253

If you want to color the top bars differently, you need to create different factors for them. For instance by pasting the supp and dose column for the OJ values:

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

hg

Upvotes: 2

Related Questions