LJA*_*LJA 3 plot r bar-chart ggplot2
我想创建一个堆叠条形图,其中我可以为沿 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)
Run Code Online (Sandbox Code Playgroud)
感谢任何建议!
谢谢,
尝试这个:
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)
Run Code Online (Sandbox Code Playgroud)
输出: