Add common legend for geom_hline in facet_grid

Hi, I'm new to R so I'm not sure if I'm doing this correctly.

I have already added a geom_hline for each facet_grid using the following code:

y = ggplot(dat, aes(x, y)) +
  theme_classic() +
  geom_boxplot(aes(fill=group)) + facet_rep_grid(.~group, scales = 'free', ) +

p1 = y +
  geom_hline(aes(yintercept=healthy.baseline.mean, linetype="Line 1"),
             linetype='dotted', color='red', show.legend = TRUE)

But the legend for the geom_hline looks something like this:
Screen Shot 2022-08-04 at 12.11.35 PM
Looks like the geom_hline for each panel in the facet_grid was supperimposed to the boxplot legend.
How can I make a separate legend for the geom_hline such that I have five boxplot legend and 1 red-dotted legend for the geom_hline?

P.S. The geom_hline is the same for all panel because it represents the mean across data group.


1 Like

Hi @jarjarbinks , try to put a reproducible example of the data, this is better way for undestand well the situation and the community could help you.

Sometimes like this:

Paste the result of dput(dat[1:30 , ] For share the first 30 rows and all columns.

Hi @M_AcostaCH

For context, I have a dataframe df containing columns namely treatment, group and index.
Basically, I drew a boxplot for each treatment and their index using facet_grid wherein each panel is separated by group.

Aside from the boxplot, I would also want to have a line plot that would indicate the baseline mean across all groups. What I did was to add a red, dotted geom_hlineon top off the geom_boxplot.

When I tried put a common legend, each boxplot legend has the red, dotted line on top of it as shown in this figure. What I would want hopefully is to have a separate red, dotted line legend.
Screen Shot 2022-08-04 at 12.11.35 PM

Here's the following code:

y = ggplot(df, aes(treatment, index)) +
  theme_classic() + labs(x = '', y = 'Index') +
  geom_boxplot(aes(fill=group)) + facet_rep_grid(.~group, scales = 'free', ) +
  scale_y_continuous(breaks = c(0, 0.25, 0.5, 0.75, round(baseline_mean,2), 1),
                     limits = c(0,1)) +
  scale_fill_manual(values=color_scheme) +
  geom_hline(aes(yintercept = baseline_mean, color = "U"), linetype='dotted', color='red') +
        strip.background = element_blank(),
        strip.text.x = element_blank(),
        axis.line.y = element_line(colour = 'black',
        axis.text.y = element_text(color = c("black", "black", "black", "black", "red", "black")) ## To color the y-tick of the baseline

Hopefully I made the problem very clear. Thank you.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.