【发布时间】:2018-12-21 23:31:52
【问题描述】:
在堆积条形图中,我试图指定不同条形的颜色。例如,治疗组的渐变绿色和对照组的渐变蓝色。但是,在指定颜色后,我丢失了图例。有没有办法把传说加回来?
# 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)
当我为每个条形指定颜色时,图例消失了。
我想要的图表如上所示。有谁知道如何找回传说?治疗组一份,对照组一份。或者有没有办法手动添加图例?
【问题讨论】:
标签: r colors bar-chart legend geom-bar