【问题标题】:Specific colours on stacked Bars in R with ggplot2使用ggplot2在R中堆叠条上的特定颜色
【发布时间】:2014-04-21 07:47:56
【问题描述】:

这是我在 R 中的代码:

prod <- read.csv("/tmp/pepper.csv",header=T,sep="\t")
png("/tmp/image.png", width=1000, height=1000)

datm <- melt(cbind(prod,ind = rownames(prod)),is.vars = c('ind'))

ggplot(datm,aes(x = codigo_inver,y = value,fill = factor(variable))) + 
  geom_bar(stat='identity', position = "fill" ) +
  coord_flip()+
  scale_colour_manual(values = c("red","orange", "green"))
dev.off()

数据集是:

green   orange  red codigo_inver
48.40   30.22   21.38   7_7726-14
32.31   28.18   39.51   8_7726-14
46.74   30.13   23.13   9_7577-4
55.13   32.80   12.06   21_7562-4
51.30   30.76   17.94   28_7614-1
40.65   37.75   21.60   30_7094-2

它会产生:

但是颜色不匹配

值 = c(“红色”、“橙色”、“绿色”)

在图片中,红色应该是绿色,绿色应该是橙色,蓝色应该是红色。

颜色必须与列名数据匹配,红色为红色,橙色为橙色,绿色为绿色。

如何将这些颜色与原始列名颜色匹配?

提前致谢!

【问题讨论】:

    标签: r colors ggplot2 dataset


    【解决方案1】:

    从因子的级别中获取颜色,并使用scale_fill_manual

    ggplot(datm,aes(x = codigo_inver,y = value,fill = factor(variable))) + 
      geom_bar(stat='identity', position = "fill" ) +
      coord_flip()+
      scale_fill_manual(values = levels(factor(datm$variable)))
    

    不过传说现在看起来有点明显了……

    【讨论】:

      【解决方案2】:

      当您使用fill 分配颜色时,您还应该使用相应的比例:

      scale_fill_manual(values = c("red","orange", "green"))
      

      现在应该可以了

      【讨论】:

      • 除了颜色顺序可能有误,您最终会得到一个带有红色方块的图例和旁边的“绿色”字样...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2014-12-08
      • 2012-05-22
      • 2014-11-17
      • 2017-04-27
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多