0

I'm working of from a return ggplot object and want to override the legend labels. I tried overriding with guides but it does not seem to work. Any way else to do this?

library ( ggplot2 ) 
    make_plot <- function (){
    g1 = ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + 
      geom_bar( ) +
      scale_fill_brewer(palette = "Set1")
    return ( g1 )
    }
    
    g1 = make_plot()

    g1 +  guides( fill = guide_legend(title.position="top"  , title ="Groups", labels=c("c","b", "c")  ) )

so what I want here is to have the legend labels changed to a b c instead of 4,5, 6

enter image description here

Ahdee
  • 4,679
  • 4
  • 34
  • 58
  • 1
    The labels are set via the `labels` argument of the scale so do `g1 + scale_fill_brewer(palette = "Set1", labels=c("c","b", "c"))`. That will give a warning but that's how it is. – stefan Feb 04 '22 at 18:34

1 Answers1

1

You can find more information here Editing legend (text) labels in ggplot or ggplot legends - change labels, order and title on changing ggplot legend labels.

But the quick answer to your question is that these could be specified in your code in scale_fill_brewer() and not guide_legend(), like this:

library ( ggplot2)

g1 = ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + 
  geom_bar() 

g1 +  
  guides(fill = guide_legend(title.position="top", title ="Groups") ) + 
  scale_fill_brewer(palette = "Set1", labels = c("a", "b", "c"))

Edited: Updated the answer in response to your comment. It is also certainly possible to do it this way after the object is created.