mwaskom / seaborn

Statistical data visualization in Python
https://seaborn.pydata.org
BSD 3-Clause "New" or "Revised" License
12.62k stars 1.94k forks source link

plt.axvspan does not work with lmplot #3719

Open loftusa opened 5 months ago

loftusa commented 5 months ago

I am on seaborn 0.13.2.

d = sns.load_dataset('penguins')
g = sns.lmplot(data=d, x='bill_length_mm', y='bill_depth_mm', row='sex', col='species')
g.map(plt.axvspan, xmin=30, xmax=50, color='green', alpha=0.2)

raises an AttributeError. However, using the same map method, the below code works:

d = sns.load_dataset('fmri')
g = sns.relplot(data=d, col='region', x='timepoint', y='signal', kind='line', row='event')
g.map(plt.axvspan, xmin=0, xmax=5, color='green', alpha=0.2)

The full error message is below.

[/Users/alex/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py:123](http://localhost:8888/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py#line=122): UserWarning: The figure layout has changed to tight
  self._figure.tight_layout(*args, **kwargs)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[177], line 5
      2 d
      4 g = sns.lmplot(data=d, x='bill_length_mm', y='bill_depth_mm', row='sex', col='species')
----> 5 g.map(plt.axvspan, xmin=30, xmax=50, color='green', alpha=0.2)

File [~/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py:758](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py#line=757), in FacetGrid.map(self, func, *args, **kwargs)
    755         plot_args = [v.values for v in plot_args]
    757     # Draw the plot
--> 758     self._facet_plot(func, ax, plot_args, kwargs)
    760 # Finalize the annotations and layout
    761 self._finalize_grid(args[:2])

File [~/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py:854](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/seaborn/axisgrid.py#line=853), in FacetGrid._facet_plot(self, func, ax, plot_args, plot_kwargs)
    852     plot_args = []
    853     plot_kwargs["ax"] = ax
--> 854 func(*plot_args, **plot_kwargs)
    856 # Sort out the supporting information
    857 self._update_legend_data(ax)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/pyplot.py:2431](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/pyplot.py#line=2430), in axvspan(xmin, xmax, ymin, ymax, **kwargs)
   2429 @_copy_docstring_and_deprecators(Axes.axvspan)
   2430 def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
-> 2431     return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/axes/_axes.py:1026](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/axes/_axes.py#line=1025), in Axes.axvspan(self, xmin, xmax, ymin, ymax, **kwargs)
   1023 (xmin, xmax), = self._process_unit_info([("x", [xmin, xmax])], kwargs)
   1025 verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
-> 1026 p = mpatches.Polygon(verts, **kwargs)
   1027 p.set_transform(self.get_xaxis_transform(which="grid"))
   1028 p.get_path()._interpolation_steps = 100

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/_api/deprecation.py:454](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/_api/deprecation.py#line=453), in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/patches.py:1093](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/patches.py#line=1092), in Polygon.__init__(self, xy, closed, **kwargs)
   1080 @_docstring.dedent_interpd
   1081 @_api.make_keyword_only("3.6", name="closed")
   1082 def __init__(self, xy, closed=True, **kwargs):
   1083     """
   1084     *xy* is a numpy array with shape Nx2.
   1085 
   (...)
   1091     %(Patch:kwdoc)s
   1092     """
-> 1093     super().__init__(**kwargs)
   1094     self._closed = closed
   1095     self.set_xy(xy)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/_api/deprecation.py:454](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/_api/deprecation.py#line=453), in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/patches.py:100](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/patches.py#line=99), in Patch.__init__(self, edgecolor, facecolor, color, linewidth, linestyle, antialiased, hatch, fill, capstyle, joinstyle, **kwargs)
     97 self.set_joinstyle(joinstyle)
     99 if len(kwargs):
--> 100     self._internal_update(kwargs)

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/artist.py:1223](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/artist.py#line=1222), in Artist._internal_update(self, kwargs)
   1216 def _internal_update(self, kwargs):
   1217     """
   1218     Update artist properties without prenormalizing them, but generating
   1219     errors as if calling `set`.
   1220 
   1221     The lack of prenormalization is to maintain backcompatibility.
   1222     """
-> 1223     return self._update_props(
   1224         kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
   1225         "{prop_name!r}")

File [~/mambaforge/lib/python3.10/site-packages/matplotlib/artist.py:1197](http://localhost:8888/~/mambaforge/lib/python3.10/site-packages/matplotlib/artist.py#line=1196), in Artist._update_props(self, props, errfmt)
   1195             func = getattr(self, f"set_{k}", None)
   1196             if not callable(func):
-> 1197                 raise AttributeError(
   1198                     errfmt.format(cls=type(self), prop_name=k))
   1199             ret.append(func(v))
   1200 if ret:

AttributeError: Polygon.set() got an unexpected keyword argument 'marker'
mwaskom commented 1 month ago

A little hacky but you can do

g.hue_kws.pop("marker")

between the lmplot call and mapping additional functions that don't support marker.