自定义分组条形图ggplot上的条形颜色?

时间:2021-02-01 05:35:07

标签: r ggplot2

我需要更改“案例”栏的颜色。例如,我希望年龄组 a 的“案例”栏为黄色,年龄组 b 的“案例”栏为蓝色,年龄组 c 的“案例”栏为绿色等。我只想让我的 ggplot 中当前为棕色的“案例”条的颜色全部为不同的颜色。

这是原始数据:

data<-data.frame("agegroup" = c("a","b","c","a","b","c"), "type" = c("case","case","case","control","control","control"), "value" = c(1,2,3,2,2,2))

这里是ggplot的代码:

ggplot(data, aes( x = agegroup, y=value, fill=type)) + 
  geom_bar(
    width = 0.4, position = position_dodge(width=0.65), stat="identity") +
  scale_y_continuous(expand = c(0,0),limits=c(0,10), breaks=seq(from=0, to= 10, by=1)) + 
  theme(legend.position = c(0.1, 0.8),
        axis.text.x=element_text(angle=60, hjust=1, size=12, face="bold"), 
        axis.title.x=element_text(margin=margin(t=10,r=20,b=20,l=20),face="bold", size=12),
        legend.text=element_text(size=8)) +
  ylab("(%)")+
  scale_fill_manual(values = c("brown4","grey25"), name="",labels=c("case","controls",""))+

Here is a photo of the graph

提前致谢。

1 个答案:

答案 0 :(得分:1)

ggplot 的角度来看,您希望填充颜色是 typeagegroup 列的组合。我们将此组合创建为单独的列,然后正常绘图:

data$fill_type = with(data, ifelse(type == "case", paste(type, agegroup), type))

ggplot(data, aes( x = agegroup, y=value, fill=fill_type)) + 
  geom_bar(
    width = 0.4, position = position_dodge(width=0.65), stat="identity") +
  scale_y_continuous(expand = c(0,0),limits=c(0,10), breaks=seq(from=0, to= 10, by=1)) + 
  theme(legend.position = c(0.1, 0.8),
        axis.text.x=element_text(angle=60, hjust=1, size=12, face="bold"), 
        axis.title.x=element_text(margin=margin(t=10,r=20,b=20,l=20),face="bold", size=12),
        legend.text=element_text(size=8)) +
  ylab("(%)")#+
  #scale_fill_manual(values = c("brown4","grey25"), name="",labels=c("case","controls",""))

enter image description here