我想创建一个堆叠的条形图,其中我可以为 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)
输出:
关于r - 有没有一种方法可以使用颜色和阴影来绘制堆叠条形图来区分类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65312775/