r - 有没有一种方法可以使用颜色和阴影来绘制堆叠条形图来区分类别?

标签 r ggplot2 plot bar-chart

我想创建一个堆叠的条形图,其中我可以为 x 轴上的类别设置不同的颜色(出于交流目的,因为它们与一组强烈颜色编码的项目相关),但我也想区分堆叠的部分具有两个类别的条形图,最好使用一种模式。我找到了使用颜色透明度的部分解决方案,但这并不是我想要的。

我发现一些解决方案使用额外的包来使用图像填充来提供复杂的填充图案,还有一些解决方法是绘制线条以位于条形上方以创建人工填充效果,还有一些解决方案允许条形具有颜色和图案填充,但只能根据条或堆栈进行拆分,而不是两者兼而有之。到目前为止,我还没有发现任何东西可以只允许对堆栈进行简单的图案填充,同时还允许条形具有不同的颜色。

例子:

mydata <- as.data.frame(cbind(letters = c("a","b","c","d","e","f","a","b","c","d","e","f"),
                              split=c("yes","yes","yes","yes","yes","yes","no","no","no","no","no","no"),
                              amount= c(2,3,5,3,4,6,7,2,5,7,2,4)))

colfill <- c("red","blue","green","orange","magenta","purple") ## fill for letters variable
## stackfill <- c("solid","striped") ## example of type of fill variable I want for for 'split'

## Make the barplots:

# this one colours bars by 'split':
ggplot(data=mydata, aes(x=letters, y=amount, fill=split)) +
  geom_bar(stat="identity",position="stack")+
  scale_fill_manual(values=colfill)

# while this one distinguished based on 'letters'
ggplot(data=mydata, aes(x=letters, y=amount, fill=letters)) +
  geom_bar(stat="identity",position="stack")+
  scale_fill_manual(values=colfill)

# I want to combine both to get something like this, with colour coded 'letters' and pattern coded 'split':
ggplot(data=mydata)+
  geom_col(aes(x=letters, y=amount, fill=letters, alpha=split)) +
  scale_alpha_discrete(range=c(1,0.5))+
  scale_fill_manual(values=colfill)

感谢任何建议!

谢谢,

最佳答案

试试这个:

library(ggplot2)
#remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
#Data
mydata <- as.data.frame(cbind(letters = c("a","b","c","d","e","f","a","b","c","d","e","f"),
                              split=c("yes","yes","yes","yes","yes","yes","no","no","no","no","no","no"),
                              amount= c(2,3,5,3,4,6,7,2,5,7,2,4)))

colfill <- c("red","blue","green","orange","magenta","purple") ## fill for letters variable
## Make the barplots:
ggplot(data=mydata)+
  geom_col(aes(x=letters, y=amount, fill=letters)) +
  geom_col_pattern(
    aes(letters, amount, pattern_fill = split,fill=letters), 
    pattern = 'stripe',
    colour  = 'black'
  )+ 
  scale_fill_manual(values=colfill)

输出:

enter image description here

关于r - 有没有一种方法可以使用颜色和阴影来绘制堆叠条形图来区分类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65312775/

相关文章:

r - 如何在具有不同 Canvas 大小的 ggplot2 图网格中保持一致的轴缩放

r - 减少ggplot2中图例列之间的空间

r - 将 `ggplot` 调用存储在 `data.frame`(或替代)中,然后对其进行评估

r - 在绘图上绘制多条线

python - 如何使用 matplotlib 启用/禁用轻松共享轴

r - R:填写时间序列中的缺失日期?

r - 如何从 R 中的矢量图形制作自定义绘图符号

r - 如何在简单的格子图中更改面板的顺序

r - 在 dplyr 中使用 get() 而不是 SE 有什么缺点吗?

r - as.Date 不保留 R 中的时间