简体   繁体   中英

ggplot2: Missing legend when specify color using fill in geom_bar

In the stacked bar chart, I am trying to specify the color for different bars. Eg, gradient green for treatment group and gradient blue for control group. However, after specifying the colors, I lost the legend. Is there a way to add legends back?

# Create data set
ID<-c(rep(1:4, 6))
Group<-c(rep(0,4), rep(1,4), rep(0,4), rep(1,4), rep(0,4), rep(1,4))
Time<-c(rep("Time 1",8), rep("Time 2",8), rep("Time 3",8))
Response<-c(1,2,3,1,2,3,1,2,2,3,3,1,1,3,2,1,2,1,3,1,2,2,1,3)

data <- data.frame(ID, Group, Time, Response)
data$Response<-as.factor(data$Response)

library(dplyr)
data1<-as.data.frame(
  data %>% 
    group_by(Group, Time, Response) %>%                     
    summarise(N= n()))

# Define the color for control and treatment groups
trtCol <- c("#3182bd", "#9ecae1", "#deebf7")
conCol <- c("#31a354", "#a1d99b", "#e5f5e0")
Palette<-c(conCol, trtCol, conCol, trtCol, conCol, trtCol)

library(ggplot2)
library(scales)

# Specify color in ggplot using "geom_bar (fill=Palette)"
ggplot(data1, aes(Group, N, fill = Response))+ 
  geom_bar(position = "fill",stat = "identity", fill=Palette) + 
  facet_wrap(~Time, strip.position = "bottom") +
  labs(title="Distribution of Responses by Groups over Time", 
       x="Time Points", y="Percentage")+
  scale_y_continuous(labels = percent_format()) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5), 
        axis.text.x=element_blank(), axis.ticks.x=element_blank(), 
        panel.spacing = unit(0.1, "lines"))+
  geom_text(aes(x=0,y=-0.05,label="Control\nGroup"), size=3.5)+
  geom_text(aes(x=1,y=-0.05,label="Treatment\nGroup"), size=3.5)

When I specify the color for each bar, The legend disappeared.

情节1

情节2

The graph I want is shown above. Does anyone know how to get the legends back? One for treatment group and one for control group. Or is there a way to manually add legend?

I'm not an expert on ggplot2 , but I think you lose the legend because you remove your aesthetic mapping in geom_bar with the argument assignment fill=Palette . Essentially, your fill aesthetic is not just by Response , but by a combination of Response and Group , because each group has a different color for the same response (which may be a questionable practice, but that's not for me to decide).

I think this code gives you what you want. I added a helper field to data1 in order to have the proper fill aesthetic. Note I needed to manually override the legend labels in scale_fill_manual

library(dplyr)
data1<- as.data.frame(data %>% 
    group_by(Group, Time, Response) %>%                     
    summarise(N= n())) %>%
  mutate(helper = as.character(group_indices(., Group, Response)))

# Define the color for control and treatment groups
trtCol <- c("#deebf7", "#9ecae1","#3182bd")
conCol <- c("#e5f5e0", "#a1d99b", "#31a354")
Palette<-c(conCol, trtCol, conCol, trtCol, conCol, trtCol)

library(ggplot2)
library(scales)

# Specify color in ggplot using "geom_bar (fill=Palette)"
ggplot(data1, aes(Group, N, fill = helper)) + 
  facet_wrap(~Time, strip.position = "bottom") +
  labs(title="Distribution of Responses by Groups over Time", x="Time Points", y="Percentage") +
  scale_fill_manual(name = "Response", values = Palette, labels = c(1, 2, 3, 1, 2, 3)) +
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_continuous(labels = percent_format()) + 
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_blank(), axis.ticks.x=element_blank(), 
        panel.spacing = unit(0.1, "lines"))+
  geom_text(aes(x=0,y=-0.05,label="Control\nGroup"), size=3.5)+
  geom_text(aes(x=1,y=-0.05,label="Treatment\nGroup"), size=3.5)

I used the code Zack suggested, and added "guides(fill=guide_legend(ncol=2))" to it. This is the graph I got

Revised graph

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM