如何在ggplot中添加多个图例标题(列)

时间:2018-07-16 13:36:06

标签: r ggplot2 colors bar-chart legend

在堆积的条形图中,治疗组和对照组有不同的颜色。对照组为绿色,治疗组为蓝色。在图例部分,我想显示两列图例,每组一个。我的代码如下所示:

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())) %>%
        mutate(helper = as.character(group_indices(., Group, Response)))

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

library(ggplot2)
library(scales) 

# Different colors for treatment and control groups    
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)+
guides(fill=guide_legend(ncol=2))

enter image description here

是否可以为每列创建图例标题? 这是我要创建的图形。有谁知道如何为图例的两列创建列名?

enter image description here

1 个答案:

答案 0 :(得分:2)

我找到了一个简单的解决方案。我仍然并排有两列传奇。我使用“ grid.text”功能向图中添加了一些文本。下面显示了我的代码。

p<-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\n\n",  values = Palette, labels = c("Very Severe", "Moderate", "None", "Very Severe", "Moderate", "None")) +
  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"), legend.text=element_text(size=11),legend.title=element_text(size=15))+
  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)+
  guides(fill=guide_legend(ncol=2))

library(grid)  
p
grid.text("Control", x = unit(0.81, "npc"), y = unit(0.54, "npc"))
grid.text("Treatment", x = unit(0.92, "npc"), y = unit(0.54, "npc"))

This is the graph with multiple legend titles I got.