Search code examples
rggplot2geom-bar

ggplot2 change colours in bar chart with scale_color_identity()


I'm using the workaround to remove diagonal lines from a ggplot legend: https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/vJnF9_HBqx4

With the following data, how do I change the colours of the groups?

# Create data #

a<-as.data.frame(c(1,1,1,2,2))
b<-as.data.frame(c("A","A","B","B","A"))
c<-as.data.frame(c(20,20,60,50,50))
a<-cbind(a,b,c)
colnames(a)<-c("X","Gp","Y")

# Plot #

ggplot(a, aes(x=X, y=Y,fill=Gp)) + 
  geom_bar(stat = "identity", aes(colour = "black")) + 
  scale_color_identity() + 
  theme(legend.key = element_rect(colour = "black", size = 1))

I have tried changing the following elements :

scale_color_identity(values=c("red","yellow"))

geom_bar(stat = "identity", aes(colour = c("red","yellow")))

geom_bar(stat = "identity", aes(colour = "black"), fill=c("red","yellow"))

but each produces an error.


Solution

  • Try this. The guides call let's you pick which scale to not have a legend. And, you can set the outline colour without aes().

    EDIT after comment about diagonal line in legend

    Based on this SO question remove diagonal line in legend, you can added the guides(fill etc. call to remove the diagonal.

    ggplot(a, aes(x=X, y=Y,fill=Gp)) + 
      geom_bar(stat = "identity", colour = "black") + 
      scale_fill_manual(values = c("red","yellow")) +
      guides(fill = guide_legend(override.aes = list(colour = NULL))) +
      guides(colour = FALSE)
    

    enter image description here