简体   繁体   English

颜色堆叠条形图,ggplot 中的每个条具有独特的颜色

[英]Colour stacked bar-chart with unique colour for each bar in ggplot

I would like to make a stacked histogram in ggplot, where each of the bars (and stacked bars) have a unique colour - using a provided hex value.我想在 ggplot 中制作一个堆叠直方图,其中每个条形(和堆叠条形)都有唯一的颜色 - 使用提供的十六进制值。

For example, take this dataframe.例如,拿这个数据框。

Pct <- c(0.8026200, 0.1973800, 0.8316421, 0.1683579)
Site <- c("A","A","B", "B")
hex <- c("#53412F", "#B4A383", "#4E3B29", "#B6A37E")
bin <- rep(c(1,2), 2)

df <- as.data.frame(cbind(Site,Pct,hex,bin))

I would like to use the hex colours specified to colour the corresponding bars.我想使用指定的十六进制颜色来为相应的条着色。

I have tried variations along these lines:我已经尝试了这些方面的变化:

ggplot()+
  geom_bar(aes(y=Pct, x=as.character(Site), fill=bin), data=df, stat="identity")+
  theme_bw() +
  scale_fill_manual("Subject", values=df$hex)

but this produces a green and red colour for each plot?但这会为每个情节产生绿色和红色?

Any help would be greatly appreciated.任何帮助将不胜感激。 Sorry if it is a simple solution - I have not got much experience with stacked barcharts.对不起,如果这是一个简单的解决方案 - 我对堆叠条形图没有太多经验。

Thank you in advance!先感谢您!

your issue comes from a little contradiction I think : you say to ggplot to attribute the aesthetic "fill" using the variable "bin".你的问题来自我认为的一个小矛盾:你说 ggplot 使用变量“bin”来归因美学“填充”。 Since "bin" only have two possibility ("1" or "2"), ggplot uses only 2 colors.由于“bin”只有两种可能性(“1”或“2”),ggplot 只使用 2 种颜色。 It uses the two firsts, which are green and red.它使用了两个第一,即绿色和红色。

I am not sure what you exactly want, but if you want a distinct color for each bar, then you have either to change "bin" like in the example below, or to give another argument to "fill", for example you can just replace "fill = bin" by "fill = hex".我不确定你到底想要什么,但是如果你想要每个条形的不同颜色,那么你要么像下面的例子一样改变“bin”,要么给“fill”提供另一个参数,例如你可以将“fill = bin”替换为“fill = hex”。 But if you want 4 colors, then the variable used in "fill" has to have 4 different values (below, I choosed "bin", and the values are 1,2,3,4).但是如果你想要4种颜色,那么“fill”中使用的变量必须有4个不同的值(下面,我选择了“bin”,值为1、2、3、4)。

Example :例子 :

Pct <- c(0.8026200, 0.1973800, 0.8316421, 0.1683579)
Site <- c("A","A","B", "B")
hex <- c("#53412F", "#B4A383", "#4E3B29", "#B6A37E")

##bin is defined in order it has a different value for each bar
bin <- c(1,2,3,4)
df <- as.data.frame(cbind(Site,Pct,hex,bin))

ggplot()+
  geom_bar(aes(y=Pct, x=as.character(Site), fill=bin)
           , data=df, stat="identity")+
  theme_bw() +
  scale_fill_manual(values=hex)

Result:结果:

在此处输入图片说明

Hope it will clarify your problem!希望它能澄清你的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM