Skip to content

Error when setting labelloc='top' #163

@ToryDeng

Description

@ToryDeng

I'm not sure if I did something wrong, but when I try to set the colorbar's label location to top, I get an error:

import ultraplot as uplt
import numpy as np
import pandas as pd

state = np.random.RandomState(51423)
data = state.normal(size=(3, 3)).cumsum(axis=0)
data = pd.DataFrame(data, columns=["a", "b", "c"])

fig, ax = uplt.subplots()
ax.heatmap(
    data, 
    cmap="ColdHot", 
    colorbar=True, 
    colorbar_kw={"length": 0.3, "label": "LABEL", "labelcolor": "red", "labelloc": "top"}
)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[75], line 10
      7 data = pd.DataFrame(data, columns=["a", "b", "c"])
      9 fig, ax = uplt.subplots()
---> 10 ax.heatmap(
     11     data, 
     12     cmap="ColdHot", 
     13     colorbar=True, 
     14     colorbar_kw={"length": 0.3, "label": "LABEL", "labelcolor": "red", "labelloc": "top"}
     15 )

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/axes/plot.py:4356, in PlotAxes.heatmap(self, aspect, *args, **kwargs)
   4351 @docstring._snippet_manager
   4352 def heatmap(self, *args, aspect=None, **kwargs):
   4353     """
   4354     %(plot.heatmap)s
   4355     """
-> 4356     obj = self.pcolormesh(*args, default_discrete=False, **kwargs)
   4357     aspect = _not_none(aspect, rc["image.aspect"])
   4358     if self._name != "cartesian":

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/internals/inputs.py:365, in _preprocess_or_redirect.<locals>._decorator.<locals>._preprocess_or_redirect(self, *args, **kwargs)
    363     kwargs["color"] = color
    364 # Call main function
--> 365 return func(self, *args, **kwargs)

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/axes/plot.py:4321, in PlotAxes.pcolormesh(self, x, y, z, **kwargs)
   4319 self._fix_patch_edges(m, **edgefix_kw, **kw)
   4320 self._add_auto_labels(m, **labels_kw)
-> 4321 self._update_guide(m, queue_colorbar=False, **guide_kw)
   4322 return m

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/axes/base.py:1719, in Axes._update_guide(self, objs, legend, legend_kw, queue_legend, colorbar, colorbar_kw, queue_colorbar)
   1717 align = colorbar_kw.pop("align", None)
   1718 queue = colorbar_kw.pop("queue", queue_colorbar)
-> 1719 self.colorbar(objs, loc=colorbar, align=align, queue=queue, **colorbar_kw)

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/axes/base.py:3118, in Axes.colorbar(self, mappable, values, loc, location, **kwargs)
   3116     self._register_guide("colorbar", (mappable, values), (loc, align), **kwargs)
   3117 else:
-> 3118     return self._add_colorbar(mappable, values, loc=loc, align=align, **kwargs)

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/internals/warnings.py:118, in _rename_kwargs.<locals>._decorator.<locals>._deprecate_kwargs_wrapper(*args, **kwargs)
    113         key_new = key_new.format(value)
    114     _warn_ultraplot(
    115         f"Keyword {key_old!r} was deprecated in version {version} and may "
    116         f"be removed in {next_release()}. Please use {key_new!r} instead."
    117     )
--> 118 return func_orig(*args, **kwargs)

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/ultraplot/axes/base.py:1254, in Axes._add_colorbar(self, mappable, values, loc, align, space, pad, width, length, shrink, label, title, reverse, rotation, grid, edges, drawedges, extend, extendsize, extendfrac, ticks, locator, locator_kw, format, formatter, ticklabels, formatter_kw, minorticks, minorlocator, minorlocator_kw, tickminor, ticklen, ticklenratio, tickdir, tickdirection, tickwidth, tickwidthratio, ticklabelsize, ticklabelweight, ticklabelcolor, labelloc, labellocation, labelsize, labelweight, labelcolor, c, color, lw, linewidth, edgefix, rasterized, **kwargs)
   1252     obj.set_label(label)
   1253 if labelloc is not None:
-> 1254     axis.set_label_position(labelloc)
   1255 axis.label.update(kw_label)
   1256 for label in axis.get_ticklabels():

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/matplotlib/axis.py:2638, in YAxis.set_label_position(self, position)
   2630 """
   2631 Set the label position (left or right)
   2632 
   (...)   2635 position : {'left', 'right'}
   2636 """
   2637 self.label.set_rotation_mode('anchor')
-> 2638 self.label.set_verticalalignment(_api.check_getitem({
   2639     'left': 'bottom', 'right': 'top',
   2640 }, position=position))
   2641 self.label_position = position
   2642 self.stale = True

File /usr/local/miniforge3/envs/experiment/lib/python3.12/site-packages/matplotlib/_api/__init__.py:183, in check_getitem(mapping, **kwargs)
    181     return mapping[v]
    182 except KeyError:
--> 183     raise ValueError(
    184         f"{v!r} is not a valid value for {k}; supported values are "
    185         f"{', '.join(map(repr, mapping))}") from None

ValueError: 'top' is not a valid value for position; supported values are 'left', 'right'

So the error info said the supported values are either left or right. But according to the document of labelloc, I should be able to use top:

  • labelloc, labellocation ({'bottom', 'top', 'left', 'right'}) – The colorbar label location. Inherits from tickloc by default. Default is toward the outside of the subplot for outer colorbars and 'bottom' for inset colorbars.

If I remove this argument, I can plot the colorbar:

ax.heatmap(
    data, 
    cmap="ColdHot", 
    colorbar=True, 
    colorbar_kw={"length": 0.3, "label": "LABEL", "labelcolor": "red"}
)

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingenhancementNew feature or request

    Type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions