简体   繁体   English

ggplot2:使用geom_bar中的填充指定颜色时缺少图例

[英]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 . 我不是ggplot2的专家,但是我认为您输掉了图例,因为您在geom_bar使用参数分配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). 本质上,您的fill美学不仅取决于Response ,而且ResponseGroup的组合,因为对于同一响应,每个组都有不同的颜色(这可能是一个有问题的做法,但这不是我要决定的)。

I think this code gives you what you want. 我认为这段代码可以为您提供所需的内容。 I added a helper field to data1 in order to have the proper fill aesthetic. 我向data1添加了一个helper字段,以具有适当的fill美感。 Note I needed to manually override the legend labels in scale_fill_manual 注意我需要手动覆盖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. 我使用了Zack建议的代码,并在其中添加了“ guides(fill = guide_legend(ncol = 2))”。 This is the graph I got 这是我得到的图

Revised graph 修改图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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