Problem Statement
Is there a way of changing the transparency of the inside of the bars in a geom_bar
barplot in ggplot2
? Basically I would like to make the "fill" be more transparent than the "color".
Minimal Working Example
# 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")
I tried using alpha
outside of aes()
but it just makes everything transparent. Bonus points if you can also make this transparency change appear in the legend!
Solution
I think I might have found a solution. The trick is to add color=language
in the aes()
. I think this effectively separates the filling color from the contour color. In this way, when we set alpha
value inside geom_bar
we get the desired effect. Here is the complete example
# 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)