dropping some levels of a factor in the legend BUT keeping them in the plot

95 views
Skip to first unread message

Gabriella Scatà

unread,
Oct 24, 2022, 4:27:14 PM10/24/22
to ggplot2
Hi,
I  am using ggplot to plot 2 items (one is values of a proportion & the other is a category --> proportions 0<q<100 for each category of K= K1 & K2).
I am using geom_col() to plot the proportions of the 2 categories in a stacked bar plot and facet_wrap() to facet by a third factor (population).

However, I want to color/fill the bars by a 4th factor that has 10 categories, BUT I want to show only 6 of those categories in the legend.

I thought I could use "breaks= c(lev1, lev2, lev3, lev4, lev5, lev6)" if I want to show in the legend only the first 6 levels of the factor I am filling the bars by, but still fill the bars by all 10 levels (see example at this link --> paragraph "Breaks": https://viz-ggplot2.rsquaredacademy.com/ggplot2-modify-legend.html) (this is because some levels are given the same colour so to make it clear i want to show only one of the 2 with the same colour)

However, when I try to use the "breaks= c(lev1, lev2, lev3, lev4, lev5, lev6)", the filling colour of my bars also change even if the values of the colours are the same!

How to fix this?
In the example at the given link it works fine...

See code below:
class(my.dataframe$Genotype) # factor

my.dataframe %>%
                              ggplot() +
                              geom_col(aes(x = indiv, y = q, fill = Genotype)) + 
                              scale_fill_manual(values = c("lightblue", "slateblue", "rosybrown1", "tomato", "black",  "gray53", "lightblue", "slateblue", "rosybrown1","tomato"), 
                              breaks = c("K1 Mismatch","K1_PURE", "K2 Mismatch", "K2_PURE", "K1 Unknown", "K2 Unknown"))
                              facet_wrap( ~ pop, scales="free_x", labeller = labeller(pop = pop.labels_NO_CHERRY2))  +
                              labs(fill = "K_mt") +
                              theme_minimal() +
                              theme(panel.spacing.x = unit(0, "lines"),
                                    axis.line = element_blank(),
                                    axis.text = element_blank(),
                                    strip.background = element_rect(fill = "transparent", color = "black"),
                                    panel.background = element_blank(),
                                    axis.title = element_blank(),
                                    panel.grid = element_blank()
                              ) 

I would really appreciate some help as I have been banging my head on this for ages!!
Thanks a lot!
Reply all
Reply to author
Forward
0 new messages