【问题标题】:Consistent color mapping in ggplotggplot中的一致颜色映射
【发布时间】:2016-08-10 23:59:58
【问题描述】:

我知道这个问题一直是asked before,但我无法得到公认的答案。这是我的数据集:

library(ggplot2)
library(scales)    
full_data<-NULL
full_data$race<-c(1,2,3,4,1,2,3,4,3,4,3,4,4)
full_data$race<-as.factor(full_data$race)
full_data$Year<-sample(2000:2005,13,replace=TRUE)
full_data$number<-sample(5:10,13,replace=TRUE)
full_data$program<-c(rep(1,6),rep(2,7))
full_data<-as.data.frame(full_data)
program1<-subset(full_data, full_data$program==1)
program2<-subset(full_data, full_data$program==2)
identical(levels(program1$race),levels(program2$race))

我确保race 的水平在每个数据集中都相同,但是当我制作两个条形图时,即使使用来自另一个答案的命名向量,条形图之间的颜色也不同。

MyPalette <- c("1" = "#5DD0B9", "2" = "#E1E7E9", "3" = "#1f78b4", 
           "4" =  "#a6cee3")

p1_chart<-ggplot(data=program1, aes(x=program1$Year, y=program1$number, fill=program1$race)) +
  geom_bar(stat="identity", position=position_dodge())+
  scale_colour_manual(values = MyPalette)
p1_chart

p2_chart<-ggplot(data=program2, aes(x=program2$Year, y=program2$number, fill=program2$race)) +
geom_bar(stat="identity", position=position_dodge())+
   scale_colour_manual(values = MyPalette)
p2_chart

我真的很感激任何想法!

【问题讨论】:

  • 你想要scale_fill_manual

标签: r ggplot2 colors


【解决方案1】:

只是为了向您展示 colour_scale 实际着色的位置,使用您的 MyPalette 作为 fill_scale:

library(RColorBrewer)

p1_chart<- ggplot(data=program1, aes(x=Year, y=number, fill=race, colour = race)) +
  geom_bar(stat="identity", position=position_dodge())+
  scale_fill_manual(values = MyPalette) +
  scale_color_brewer(palette = "Dark2") +
  theme_bw()
p1_chart

p2_chart<-ggplot(data=program2, aes(x=Year, y=number, fill=race, colour = race)) +
  geom_bar(stat="identity", position=position_dodge())+
  scale_fill_manual(values = MyPalette) +
  scale_color_brewer(palette = "Dark2") +
  theme_bw()
p2_chart

旁注:您并不想在 ggplot 调用中使用 df$references,因为您已经设置了 data = df。

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多