Eul*_*ter 6 plot r bar-chart ggplot2
geom_bar有没有办法改变条形图中条形内部的透明度ggplot2?基本上我想让“填充”比“颜色”更透明。
# Create fake data
df <- data.frame(language=c("Python", "Python", "R", "Julia", "R"),
filetype=c("Script", "Notebook", "Notebook", "Script", "Script"),
count=c(3,10,4,2,1))
# Make a barplot with ggplot
ggplot(data=df) +
geom_bar(aes(x=filetype, y=count, fill=language), position="dodge", stat="identity")
Run Code Online (Sandbox Code Playgroud)
我尝试使用alpha外部,aes()但它只是使一切变得透明。如果您还可以使这种透明度变化出现在图例中,那就加分了!
我想我可能已经找到了解决方案。诀窍是添加color=language到aes(). 我认为这有效地将填充颜色与轮廓颜色分开。这样,当我们alpha在里面设置value的时候geom_bar就可以得到想要的效果了。这是完整的例子
# Create fake data
df <- data.frame(language=c("Python", "Python", "R", "Julia", "R"),
filetype=c("Script", "Notebook", "Notebook", "Script", "Script"),
count=c(3,10,4,2,1))
# Make a barplot with ggplot
ggplot(data=df) +
geom_bar(aes(x=filetype, y=count, fill=language, color=language),
position="dodge", stat="identity", alpha=0.2)
Run Code Online (Sandbox Code Playgroud)
一种选择是添加另一层。
ggplot(data=df, aes(x = filetype, y = count, fill = language, color = language)) +
geom_col(
position = position_dodge(preserve = "single"),
alpha = 0.1
) +
# geom_col(
# position = position_dodge(preserve = "single"),
# fill = NA
# ) +
NULL
Run Code Online (Sandbox Code Playgroud)
结果
我又添加了两个奖励积分:
1)geom_col()代替geom_bar(... stat="identity")
2)position_dodge(preserve = "single")保持各组的条形宽度一致
编辑
如果我们想要更少的代码,黑色边框,透明fill,并保持栏在中心对齐,我们可以使用
ggplot(data=df, aes(x = filetype, y = count, fill = language)) +
geom_col(
position = position_dodge2(preserve = "single"),
alpha = 0.1,
color = "black"
)
Run Code Online (Sandbox Code Playgroud)
输出