Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205399

R ggplot geom_bar: Change transparency inside bars, keeping contour/boundary the same

$
0
0

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")

enter image description here

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)

enter image description here


Viewing all articles
Browse latest Browse all 205399

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>