NREL / tyche

https://nrel.github.io/tyche-docs/
MIT License
3 stars 1 forks source link

AttributeError (etc) thrown by one seaborn plot in template decision context analysis notebook #188

Open rjhanes opened 7 months ago

rjhanes commented 7 months ago

This graph doesn't seem to want to generate:

g = sb.boxplot(
    x="Tranche",
    y="Value",
    dodge=True,
    cut=0,
    data=tranche_results.xs(
        ("Delta Overall Efficiency", "Technology A"),
        level=["Index", "Technology"]
    ).reset_index(
    )[["Tranche", "Value"]],
    order=[
        'Component B0 Low Funding',
        'Component B0 Medium Funding',
        'Component B0 High Funding',
        'Component B1 Low Funding',
        'Component B1 Medium Funding',
        'Component B1 High Funding',
        'Component B2 Low Funding',
        'Component B2 Medium Funding',
        'Component B2 High Funding',
    ]
)
g.set(ylabel="Change in Overall Efficiency\nRelative to Current State",
     title="Overall Efficiency Progress (Technology A Only)\n with Component B0, B1, B2 R&D")
g.set_xticklabels(g.get_xticklabels(), rotation=30, ha='right', rotation_mode='anchor')
g.axhline(y=0, linestyle=":", label='Current State')
g.legend()

Box, Boxen, Violin, Swarm all throw an error, but not the same one, see below

I can't remember if this plot was working correctly at one time (originally it was boxen) and perhaps a package update broke it, or if the plot was never working - although since it's in the middle of the notebook, the former is more likely.

Plan of attack:

Boxen:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[21], line 1
----> 1 g = sb.boxenplot(
      2     x="Tranche",
      3     y="Value",
      4     dodge=True,
      5     cut=0,
      6     data=tranche_results.xs(
      7         ("Delta Overall Efficiency", "Technology A"),
      8         level=["Index", "Technology"]
      9     ).reset_index(
     10     )[["Tranche", "Value"]],
     11     order=[
     12         'Component B0 Low Funding',
     13         'Component B0 Medium Funding',
     14         'Component B0 High Funding',
     15         'Component B1 Low Funding',
     16         'Component B1 Medium Funding',
     17         'Component B1 High Funding',
     18         'Component B2 Low Funding',
     19         'Component B2 Medium Funding',
     20         'Component B2 High Funding',
     21     ]
     22 )
     23 g.set(ylabel="Change in Overall Efficiency\nRelative to Current State",
     24      title="Overall Efficiency Progress (Technology A Only)\n with Component B0, B1, B2 R&D")
     25 g.set_xticklabels(g.get_xticklabels(), rotation=30, ha='right', rotation_mode='anchor')

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:1940, in boxenplot(data, x, y, hue, order, hue_order, orient, color, palette, saturation, fill, dodge, width, gap, linewidth, linecolor, width_method, k_depth, outlier_prop, trust_alpha, showfliers, hue_norm, log_scale, native_scale, formatter, legend, scale, box_kws, flier_kws, line_kws, ax, **kwargs)
   1932 color = _default_color(
   1933     ax.fill_between, hue, color,
   1934     {},  # TODO how to get default color?
   1935     # {k: v for k, v in kwargs.items() if k in ["c", "color", "fc", "facecolor"]},
   1936     saturation=saturation,
   1937 )
   1938 linecolor = p._complement_color(linecolor, color, p._hue_map)
-> 1940 p.plot_boxens(
   1941     width=width,
   1942     dodge=dodge,
   1943     gap=gap,
   1944     fill=fill,
   1945     color=color,
   1946     linecolor=linecolor,
   1947     linewidth=linewidth,
   1948     width_method=width_method,
   1949     k_depth=k_depth,
   1950     outlier_prop=outlier_prop,
   1951     trust_alpha=trust_alpha,
   1952     showfliers=showfliers,
   1953     box_kws=box_kws,
   1954     flier_kws=flier_kws,
   1955     line_kws=line_kws,
   1956     plot_kws=kwargs,
   1957 )
   1959 p._add_axis_labels(ax)
   1960 p._adjust_cat_axis(ax, axis=p.orient)

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:796, in _CategoricalPlotter.plot_boxens(self, width, dodge, gap, fill, color, linecolor, linewidth, width_method, k_depth, outlier_prop, trust_alpha, showfliers, box_kws, flier_kws, line_kws, plot_kws)
    791 pos_data = pd.DataFrame({
    792     self.orient: [sub_vars[self.orient]],
    793     "width": [width * self._native_width],
    794 })
    795 if dodge:
--> 796     self._dodge(sub_vars, pos_data)
    797 if gap:
    798     pos_data["width"] *= 1 - gap

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:391, in _CategoricalPlotter._dodge(self, keys, data)
    389 def _dodge(self, keys, data):
    390     """Apply a dodge transform to coordinates in place."""
--> 391     hue_idx = self._hue_map.levels.index(keys["hue"])
    392     n = len(self._hue_map.levels)
    393     data["width"] /= n

AttributeError: 'NoneType' object has no attribute 'index'

Box:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[22], line 1
----> 1 g = sb.boxplot(
      2     x="Tranche",
      3     y="Value",
      4     dodge=True,
      5     cut=0,
      6     data=tranche_results.xs(
      7         ("Delta Overall Efficiency", "Technology A"),
      8         level=["Index", "Technology"]
      9     ).reset_index(
     10     )[["Tranche", "Value"]],
     11     order=[
     12         'Component B0 Low Funding',
     13         'Component B0 Medium Funding',
     14         'Component B0 High Funding',
     15         'Component B1 Low Funding',
     16         'Component B1 Medium Funding',
     17         'Component B1 High Funding',
     18         'Component B2 Low Funding',
     19         'Component B2 Medium Funding',
     20         'Component B2 High Funding',
     21     ]
     22 )
     23 g.set(ylabel="Change in Overall Efficiency\nRelative to Current State",
     24      title="Overall Efficiency Progress (Technology A Only)\n with Component B0, B1, B2 R&D")
     25 g.set_xticklabels(g.get_xticklabels(), rotation=30, ha='right', rotation_mode='anchor')

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:1619, in boxplot(data, x, y, hue, order, hue_order, orient, color, palette, saturation, fill, dodge, width, gap, whis, linecolor, linewidth, fliersize, hue_norm, native_scale, log_scale, formatter, legend, ax, **kwargs)
   1612 color = _default_color(
   1613     ax.fill_between, hue, color,
   1614     {k: v for k, v in kwargs.items() if k in ["c", "color", "fc", "facecolor"]},
   1615     saturation=saturation,
   1616 )
   1617 linecolor = p._complement_color(linecolor, color, p._hue_map)
-> 1619 p.plot_boxes(
   1620     width=width,
   1621     dodge=dodge,
   1622     gap=gap,
   1623     fill=fill,
   1624     whis=whis,
   1625     color=color,
   1626     linecolor=linecolor,
   1627     linewidth=linewidth,
   1628     fliersize=fliersize,
   1629     plot_kws=kwargs,
   1630 )
   1632 p._add_axis_labels(ax)
   1633 p._adjust_cat_axis(ax, axis=p.orient)

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:637, in _CategoricalPlotter.plot_boxes(self, width, dodge, gap, fill, whis, color, linecolor, linewidth, fliersize, plot_kws)
    635 data = pd.DataFrame({self.orient: positions, "width": orig_width})
    636 if dodge:
--> 637     self._dodge(sub_vars, data)
    638 if gap:
    639     data["width"] *= 1 - gap

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:391, in _CategoricalPlotter._dodge(self, keys, data)
    389 def _dodge(self, keys, data):
    390     """Apply a dodge transform to coordinates in place."""
--> 391     hue_idx = self._hue_map.levels.index(keys["hue"])
    392     n = len(self._hue_map.levels)
    393     data["width"] /= n

AttributeError: 'NoneType' object has no attribute 'index'

Violin:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[23], line 1
----> 1 g = sb.violinplot(
      2     x="Tranche",
      3     y="Value",
      4     dodge=True,
      5     cut=0,
      6     data=tranche_results.xs(
      7         ("Delta Overall Efficiency", "Technology A"),
      8         level=["Index", "Technology"]
      9     ).reset_index(
     10     )[["Tranche", "Value"]],
     11     order=[
     12         'Component B0 Low Funding',
     13         'Component B0 Medium Funding',
     14         'Component B0 High Funding',
     15         'Component B1 Low Funding',
     16         'Component B1 Medium Funding',
     17         'Component B1 High Funding',
     18         'Component B2 Low Funding',
     19         'Component B2 Medium Funding',
     20         'Component B2 High Funding',
     21     ]
     22 )
     23 g.set(ylabel="Change in Overall Efficiency\nRelative to Current State",
     24      title="Overall Efficiency Progress (Technology A Only)\n with Component B0, B1, B2 R&D")
     25 g.set_xticklabels(g.get_xticklabels(), rotation=30, ha='right', rotation_mode='anchor')

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:1755, in violinplot(data, x, y, hue, order, hue_order, orient, color, palette, saturation, fill, inner, split, width, dodge, gap, linewidth, linecolor, cut, gridsize, bw_method, bw_adjust, density_norm, common_norm, hue_norm, formatter, log_scale, native_scale, legend, scale, scale_hue, bw, inner_kws, ax, **kwargs)
   1752 kde_kws = dict(cut=cut, gridsize=gridsize, bw_method=bw_method, bw_adjust=bw_adjust)
   1753 inner_kws = {} if inner_kws is None else inner_kws.copy()
-> 1755 p.plot_violins(
   1756     width=width,
   1757     dodge=dodge,
   1758     gap=gap,
   1759     split=split,
   1760     color=color,
   1761     fill=fill,
   1762     linecolor=linecolor,
   1763     linewidth=linewidth,
   1764     inner=inner,
   1765     density_norm=density_norm,
   1766     common_norm=common_norm,
   1767     kde_kws=kde_kws,
   1768     inner_kws=inner_kws,
   1769     plot_kws=kwargs,
   1770 )
   1772 p._add_axis_labels(ax)
   1773 p._adjust_cat_axis(ax, axis=p.orient)

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:988, in _CategoricalPlotter.plot_violins(self, width, dodge, gap, split, color, fill, linecolor, linewidth, inner, density_norm, common_norm, kde_kws, inner_kws, plot_kws)
    980 data = pd.DataFrame({
    981     self.orient: violin["position"],
    982     value_var: violin["support"],
    983     "density": violin["density"],
    984     "width": real_width,
    985 }, index=index)
    987 if dodge:
--> 988     self._dodge(violin["sub_vars"], data)
    989 if gap:
    990     data["width"] *= 1 - gap

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:391, in _CategoricalPlotter._dodge(self, keys, data)
    389 def _dodge(self, keys, data):
    390     """Apply a dodge transform to coordinates in place."""
--> 391     hue_idx = self._hue_map.levels.index(keys["hue"])
    392     n = len(self._hue_map.levels)
    393     data["width"] /= n

AttributeError: 'NoneType' object has no attribute 'index'

Swarm:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[24], line 1
----> 1 g = sb.swarmplot(
      2     x="Tranche",
      3     y="Value",
      4     dodge=True,
      5     cut=0,
      6     data=tranche_results.xs(
      7         ("Delta Overall Efficiency", "Technology A"),
      8         level=["Index", "Technology"]
      9     ).reset_index(
     10     )[["Tranche", "Value"]],
     11     order=[
     12         'Component B0 Low Funding',
     13         'Component B0 Medium Funding',
     14         'Component B0 High Funding',
     15         'Component B1 Low Funding',
     16         'Component B1 Medium Funding',
     17         'Component B1 High Funding',
     18         'Component B2 Low Funding',
     19         'Component B2 Medium Funding',
     20         'Component B2 High Funding',
     21     ]
     22 )
     23 g.set(ylabel="Change in Overall Efficiency\nRelative to Current State",
     24      title="Overall Efficiency Progress (Technology A Only)\n with Component B0, B1, B2 R&D")
     25 g.set_xticklabels(g.get_xticklabels(), rotation=30, ha='right', rotation_mode='anchor')

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\categorical.py:2220, in swarmplot(data, x, y, hue, order, hue_order, dodge, orient, color, palette, size, edgecolor, linewidth, hue_norm, log_scale, native_scale, formatter, legend, warn_thresh, ax, **kwargs)
   2217 palette, hue_order = p._hue_backcompat(color, palette, hue_order)
   2219 p.map_hue(palette=palette, order=hue_order, norm=hue_norm)
-> 2220 color = _default_color(ax.scatter, hue, color, kwargs)
   2221 edgecolor = p._complement_color(edgecolor, color, p._hue_map)
   2223 kwargs.setdefault("zorder", 3)

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\seaborn\utils.py:128, in _default_color(method, hue, color, kws, saturation)
    122 scout_size = max(
    123     np.atleast_1d(kws.get(key, [])).shape[0]
    124     for key in ["s", "c", "fc", "facecolor", "facecolors"]
    125 )
    126 scout_x = scout_y = np.full(scout_size, np.nan)
--> 128 scout = method(scout_x, scout_y, **kws)
    129 facecolors = scout.get_facecolors()
    131 if not len(facecolors):
    132     # Handle bug in matplotlib <= 3.2 (I think)
    133     # This will limit the ability to use non color= kwargs to specify
    134     # a color in versions of matplotlib with the bug, but trying to
    135     # work out what the user wanted by re-implementing the broken logic
    136     # of inspecting the kwargs is probably too brittle.

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\matplotlib\__init__.py:1423, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1420 @functools.wraps(func)
   1421 def inner(ax, *args, data=None, **kwargs):
   1422     if data is None:
-> 1423         return func(ax, *map(sanitize_sequence, args), **kwargs)
   1425     bound = new_sig.bind(ax, *args, **kwargs)
   1426     auto_label = (bound.arguments.get(label_namer)
   1427                   or bound.kwargs.get(label_namer))

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\matplotlib\axes\_axes.py:4634, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
   4630         keys_str = ", ".join(f"'{k}'" for k in extra_keys)
   4631         _api.warn_external(
   4632             "No data for colormapping provided via 'c'. "
   4633             f"Parameters {keys_str} will be ignored")
-> 4634 collection._internal_update(kwargs)
   4636 # Classic mode only:
   4637 # ensure there are margins to allow for the
   4638 # finite size of the symbols.  In v2.x, margins
   4639 # are present by default, so we disable this
   4640 # scatter-specific override.
   4641 if mpl.rcParams['_internal.classic_mode']:

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\matplotlib\artist.py:1186, in Artist._internal_update(self, kwargs)
   1179 def _internal_update(self, kwargs):
   1180     """
   1181     Update artist properties without prenormalizing them, but generating
   1182     errors as if calling `set`.
   1183 
   1184     The lack of prenormalization is to maintain backcompatibility.
   1185     """
-> 1186     return self._update_props(
   1187         kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
   1188         "{prop_name!r}")

File ~\AppData\Local\anaconda3\envs\tyche2\lib\site-packages\matplotlib\artist.py:1160, in Artist._update_props(self, props, errfmt)
   1158             func = getattr(self, f"set_{k}", None)
   1159             if not callable(func):
-> 1160                 raise AttributeError(
   1161                     errfmt.format(cls=type(self), prop_name=k))
   1162             ret.append(func(v))
   1163 if ret:

AttributeError: PathCollection.set() got an unexpected keyword argument 'cut'