首页 文章

R中的堆叠条上的特定颜色与ggplot2

提问于
浏览
0

这是我在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

它产生:

enter image description here

但颜色不匹配

values = c(“红色”,“橙色”,“绿色”)

在图片中,红色应为绿色,绿色应为橙色,蓝色应为红色 .

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

如何将此颜色与原始列名称颜色匹配?

提前致谢!

2 回答

  • 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)))
    

    enter image description here

    然而传说现在看起来有点明显......

  • 1

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

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

    现在它应该工作

相关问题