Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong border colors on geom_bar plot in ggplot2

Tags:

r

ggplot2

I am plotting a bar chart of counts of fish in various length categories by sampling week.
Here is a bit of the database called Chin:

Trib    Week   Size2  
MM      21     90
SM      21     80
SM      22     100
NM      22     8p

I have converted Size2 to a factor called Fork, and week to a factor called period.

Here is my code:

period<-as.factor(Chin$week)
Chin1<-cbind(Chin, period)
Fork<-as.factor(Chin$Size2)

g <- ggplot(Chin1, aes(period))
g + geom_bar(aes(fill=Fork))+ theme(axis.text.x = element_text(angle=65, 
 vjust=0.6)) +  theme_bw() +scale_fill_manual(values=c("white","gray90", 
"gray82", "gray61", "gray48", "black"))

This works great except there is no border around the bars or the elements of the legend:

Chart with no borders

But when I add colour="black" in this line to get black borders:

g + geom_bar(aes(fill=Fork, colour="black"))+ theme(axis.text.x 
element_text(angle=65, vjust=0.6))....

I instead get red borders with a new legend with an item called "black" I get this no matter what color I choose. The name of the legend item changes (i.e. blue, green) but the border color stays red and the legend item fill is still black. See below. I know this must be a simple silly mistake, but I cannot figure it out. Any ideas? Thanks in advance!

Chart with red borders

like image 410
user10124154 Avatar asked Sep 14 '25 17:09

user10124154


1 Answers

Move the colour="black" outside the aes() statement. aes() uses variables from your data to create aesthetics, so you're saying to base color off of the column "black", which doesn't exist.

Also found here

like image 186
Lost Avatar answered Sep 17 '25 07:09

Lost