0

I am coding in python's plotnine, but hoping that R ggplotters may also be able to offer a solution.

Consider the below plot. It has two states, 'pass' and 'fail' and I want to highlight the 'fail' state. I don't really need the legend to include both pass and fail as it is obvious in the context, but rather, I would like the legend to just display the violet-red dot and 'fail' to avoid any confusion.

I could do this manually by removing the legend altogether and annotating a dot and some text, but I am looking for a better way. Also, this method couldn't be used to put the legend outside of the plotting area.

How could I remove one element (the 'pass' element) in the legend below?

I did look at some ggplot solutions with breaks in the scale_fill_manual line, but I couldn't get this to work.

import numpy as np
import pandas as pd
from plotnine import *

df = pd.DataFrame({
    'x': np.random.normal(10,3,125),
    'y': np.random.normal(10,3,125),
})
df['status'] = np.where( (df['x']<7.5) & (df['y']<7.5), 'fail', 'pass')


p = (ggplot(df, aes(x='x', y='y'))
  + theme_light()
  + geom_point(aes(color='status', fill='status'))
  + labs(x=None, y=None)
  + scale_color_manual(('#891446','#0096FF'))
  + scale_fill_manual(('#891446','#0096FF'))
  + theme(
      legend_title=element_blank(),
      legend_position=(0.165,0.83),
      legend_key_size=0.1,
      legend_background=element_blank(),
      legend_box_background=element_blank(),
  )
)
p

enter image description here

brb
  • 1,123
  • 17
  • 40
  • 1
    Default way to achieve that in `ggplot2` would be to set the categories to be displayed in the legend via the `breaks` argument. Just tried that for plotnine but unfortunately doing so will also affect the limits, i.e. when adding `breaks=['fail']` the `pass` points are removed. – stefan Oct 03 '22 at 09:04
  • Thanks. Yeah, I did try break as well without success. Bugger. May have to do the bodgy manual way. Appreciate you taking a look. – brb Oct 03 '22 at 11:38
  • 1
    `breaks=['fail']` is the right way to do it. It has not worked for the `scale_color_manual` because of a bug, which has been fixed! though has not yet shipped. You can get away with `limits=['fail']`, but the fix will change the behaviour. Or, if you do not care about the exact colors you can play around with `scale_color_hue` and the `h`, `l` & `s` parameters to get a good pair of colors. – has2k1 Oct 04 '22 at 10:32

0 Answers0