FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[Bug]: Getting TypeError when creating filled colorbar for contour() plot · Issue #21932 · matplotlib/matplotlib · GitHub

Repository navigation

[Bug]: Getting TypeError when creating filled colorbar for contour() plot #21932

Open

Description

Bug summary

When trying to create a filled colorbar for a contour plot, I get this:

TypeError: Dimensions of C (13, 1) are incompatible with X (2) and/or Y (13); see help(pcolormesh)

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

x = np.arange(10.0)
mat = np.hypot(x, x[:, None])
plt.xlim(-1, 10)
plt.ylim(-1, 10)

plt.figure(1, clear=True)
cntr = plt.contour(x, x, mat, levels=np.arange(13) + 0.5, cmap=cm.PRGn)

# for a solid colorbar:
cbar = plt.colorbar()
cbar.filled = True
cbar.draw_all()

Actual outcome

Python 3.8.12 (default, Oct 12 2021, 13:49:34)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.29.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: run tt

TypeError Traceback (most recent call last)
~/code/pyyeti/tt.py in
14 cbar = plt.colorbar()
15 cbar.filled = True
---> 16 cbar.draw_all()

~/anaconda3/lib/python3.8/site-packages/matplotlib/colorbar.py in draw_all(self)
597 if self._extend_upper():
598 ind = ind[:-1]
--> 599 self._add_solids(X, Y, self._values[ind, np.newaxis])
600
601 def _add_solids(self, X, Y, C):

~/anaconda3/lib/python3.8/site-packages/matplotlib/colorbar.py in _add_solids(self, X, Y, C)
613 self._add_solids_patches(X, Y, C, mappable)
614 else:
--> 615 self.solids = self.ax.pcolormesh(
616 X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha,
617 edgecolors='none', shading='flat')

~/anaconda3/lib/python3.8/site-packages/matplotlib/init.py in inner(ax, data, *args, **kwargs)
1410 def inner(ax, *args, data=None, **kwargs):
1411 if data is None:
-> 1412 return func(ax, *map(sanitize_sequence, args), **kwargs)
1413
1414 bound = new_sig.bind(ax, *args, **kwargs)

~/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in pcolormesh(self, alpha, norm, cmap, vmin, vmax, shading, antialiased, *args, **kwargs)
6014 kwargs.setdefault('edgecolors', 'none')
6015
-> 6016 X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
6017 shading=shading, kwargs=kwargs)
6018 coords = np.stack([X, Y], axis=-1)

~/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in _pcolorargs(self, funcname, shading, *args, **kwargs)
5527 if shading == 'flat':
5528 if (Nx, Ny) != (ncols + 1, nrows + 1):
-> 5529 raise TypeError('Dimensions of C %s are incompatible with'
5530 ' X (%d) and/or Y (%d); see help(%s)' % (
5531 C.shape, Nx, Ny, funcname))

TypeError: Dimensions of C (13, 1) are incompatible with X (2) and/or Y (13); see help(pcolormesh)

In [2]:

Expected outcome

No errors and have a properly filled colorbar.

Additional information

This method worked before v3.5.0.

Operating system

Ubuntu: 5.4.0-91-generic #102-Ubuntu SMP Fri Nov 5 16:31:28 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Matplotlib Version

3.5.0

Matplotlib Backend

Qt5Agg

Python version

Python 3.8.12

Jupyter version

No response

Installation

conda

Activity

  1. jklymak commented on Dec 12, 2021

    Member

    Why are you calling draw_all here? Did this ever work without draw_all? Did this ever work at all, and if so do you know which version? It did not work, so far as I can tell, in 3.4.3, so that eliminates the recent colorbar rewrite as the proximate cause.

    Can you tell us what you are after? It seems you want unfilled contours, but the colorbar to be solid? Thats certainly not something we directly test or document. If this used to work, then I guess this is a bug report. If it never worked it is a feature request.

    I think its fair to say that some of our public colorbar API should not be. I don't think users should be able to toggle the "filled" attribute and expect anything sensible, and I dont know why they would need or want to call cb.draw_all()

  2. jklymak commented on Dec 12, 2021

    Member

    I can confirm this used to work in 3.3. But that you indeed needed to both call cbar.filled=True and car.draw_all() or it does not fill.

    Indeed in 3.3 we explicitly disallowed filled from the colorbar signature, so it seems an oversight that cbar.filled was left public as well:

    The 'filled' parameter to Colorbar has no effect because it is overridden by the mappable; it is deprecated since 3.3 and will be removed two minor releases later.
    
      1. we should deprecate filled and draw_all as public API
      1. we should consider how to give users a filled colorbar, even if their mappable is contour lines (perhaps by re-instating the "filled" kwarg to colorbar).
  3. twmacro commented on Dec 12, 2021

    Author

    Thank you @jklymak for looking at this. I believe you answered most the questions you had for me. I vote "Yes" on your thought about re-instating the "filled" kwarg to colorbar. No problem with deprecating filled and draw_all public API options either.

    For the information I'm trying to communicate, I think contour is better than contourf (lots of whitespace where nothing is going on is great for my application). And for the colorbar, I simply prefer the filled one for aesthetic reasons. Plus, maybe it's just me, but it's less work for my brain to quickly assimilate.

    I wrote a little script (included below) to compare 3 options. I prefer the 3rd plot:

    With default contour & colorbar:

    With default contourf & colorbar:

    With contour & a filled colorbar:

    Even with the deprecation of filled and draw_all public API options, it looks like I'll still be able to make a filled colorbar ... it'll be just a little painful (see code below).

    Here is the code:

    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    x = np.arange(10.0)
    mat = np.hypot(x, x[:, None])
    figsize = (4, 3)
    
    plt.figure(1, clear=True, figsize=figsize)
    plt.contour(x, x, mat, levels=np.arange(13) + 0.5, cmap=cm.plasma)
    plt.colorbar()
    plt.savefig("fig1.png")
    
    plt.figure(2, clear=True, figsize=figsize)
    plt.contourf(x, x, mat, levels=np.arange(13) + 0.5, cmap=cm.plasma)
    plt.colorbar()
    plt.savefig("fig2.png")
    
    plt.figure(3, clear=True, figsize=figsize)
    cs = plt.contour(x, x, mat, levels=np.arange(13) + 0.5, cmap=cm.plasma)
    norm = matplotlib.colors.Normalize(vmin=cs.cvalues.min(), vmax=cs.cvalues.max())
    sm = plt.cm.ScalarMappable(norm=norm, cmap=cs.cmap)
    cb = plt.colorbar(sm)  # , ticks=cs.levels)
    plt.savefig("fig3.png")
    
  4. jklymak commented on Dec 12, 2021

    Member

    Yeah, the 3.3. behaviour was:

    I'm not sure that makes much sense. The behaviour of a continuous map is kind of nice. Or centering the blocks...

  5. timhoffm commented on Dec 12, 2021

    Member

    Agreed that the 3.3 behavior doesn't make much sense.

    The continuous map is conceptually nice: "We have colors for all values, the contours simply take out the appropriate color.". However, it's harder to estimate the associated color compared to blocks. To be checked/discussed: How to handle contours with explicit colors set.

    OTOH, blocks do not have cananoical boundaries. That could become complicated when using non-uniform levels.

    I see arguments for both variants but threre are some caveats as well.

    Using a detached colormap with a separate ScalarMappable is a second-best option only. Colors can get out of sync, in particular also because we have colorbar zooming now.

  6. twmacro commented on Dec 13, 2021

    Author

    @jklymak, I like your idea of the centering the blocks. I also like the continuous map. I'm not sure which I'd prefer in the end.

    @timhoffm, I am also concerned about the detached colorbar. In fact, I was so concerned that I took the colorbars I generated above via a screen shot and put them side-by-side with GIMP for a visual color comparison. By blowing it up 400%, I was convinced the colors were perfect in the continuous map. I see your point about getting out of sync though, and that does concern me in general. For my application however, I save these plots for inclusion into reports, so I think I'm okay for the short term.

  7. greglucas commented on Dec 13, 2021

    Contributor

    I can see people wanting all three cases above, so there should probably be a way to support them all... I personally don't like the colorbars with thin lines, but that is a personal preference and I'm sure there are people that like that style. To me, that seems more amenable to a legend call than a colorbar call. I also agree the blocks of colors being centered would be nice too.

    A contourset is a scalarmappable, so it should be easy enough to add a continuous colorbar, the issue is that there is currently logic in the colorbar code that handles contourset's differently than a normal mappable. The filled blocks not being centered shouldn't be too hard to update either, it could be a shift of the ticks or moving the boundaries of the blocks of colors.

    Re: Explicit colors set in contour: It looks like a listed colormap is created in contourset when this happens, so there is a cmap that is attached for reference still that the colorbar can utilize.

    Re: Zooming/panning on colorbar: That is explicitly disabled for contours due to the discrete levels, so you can't interact with contour(f) plots currently.

  8. changed the title [-][Bug]: Getting TypeError when creating filled colorbar for contour() plot in Matplotlib 3.5.0[/-] [+][Bug]: Getting TypeError when creating filled colorbar for contour() plot[/+] on Dec 14, 2021
  9. github-actions commented on Nov 12, 2025

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  10. added
    status: closed as inactiveIssues closed by the "Stale" Github Action. Please comment on any you think should still be open.
    on Dec 13, 2025
  11. added
    keepItems to be ignored by the “Stale” Github Action
    on Dec 13, 2025
  12. removed
    status: inactiveMarked by the “Stale” Github Action
    status: closed as inactiveIssues closed by the "Stale" Github Action. Please comment on any you think should still be open.
    on Dec 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    keepItems to be ignored by the “Stale” Github Actiontopic: color/colorbar

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions


      Back | FazBrowse Home | New Git URL