绘制水平条形图的给定颜色并使用 ggplot2 将未绘制区域用灰色着色

Posted

技术标签:

【中文标题】绘制水平条形图的给定颜色并使用 ggplot2 将未绘制区域用灰色着色【英文标题】:plotting the given color for horizontal bar graph and coloring the unplotted area with grey using ggplot2 【发布时间】:2015-05-27 16:02:44 【问题描述】:

我有数据集Global如下;

Win.Rate    Perc    bar.color
0-25         11%    Green
25-50         8%    Red
50-75        47%    Yellow
75-100       86%    Green

首先,我希望条形图颜色与bar.color 列中的对应颜色一致。

其次,我想在绘制给定值后为条形图添加灰色。

例如,在剩余区域的条形图上用绿色绘制 11% 之后,我希望它用灰色着色。

基于this post

我试过下面的代码

   Global$diff = 100 -   
             as.numeric(substr(Global$Perc,0,nchar(Global$Perc)-1))
   library(reshape)
   melt_data <- melt(Global,id="Win.Rate")

但我收到一条错误消息:

Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(1L, 1L, 1L, 1L, 2L, 2L, 2L,  :
  invalid factor level, NA generated

【问题讨论】:

【参考方案1】:

要获得你想要的情节,你不需要使用melt。但是要回答您最直接的问题,您收到错误的原因是因为您试图将所有Percbar.colordiff 堆叠到一个名为value 的列中。 Percbar.color 可能是 factor,而 diffnumeric,这会导致问题,因为一列只能有一种类型,而 melt 很难确定它是哪一种你想要的。

但这里有一个你想要的解决方案:

# Read in data
Global <- read.table(textConnection("Win.Rate    Perc    bar.color
0-25         11%    Green
25-50         8%    Red
50-75        47%    Yellow
75-100       86%    Green"), header=TRUE)

library(ggplot2)
# A cleaner version of your diff
Global$percentage <- as.numeric(gsub('%','',Global$Perc))
ggplot(Global, aes(x=Win.Rate, y=percentage)) + 
  geom_bar(stat="identity", fill="grey", aes(y=100)) +
  geom_bar(stat="identity", fill=Global$bar.color) +
  coord_flip() + theme_classic()

【讨论】:

非常感谢@nograpes 这是我真正想要的。它帮助了我。 如果您喜欢,可以点击问题左侧的复选框。

以上是关于绘制水平条形图的给定颜色并使用 ggplot2 将未绘制区域用灰色着色的主要内容,如果未能解决你的问题,请参考以下文章