getting a matplotlib colorbar tick outside data limits for use with boundaries keyword

2024/10/12 8:19:09

I am trying to use a colorbar to label discrete, coded values plotted using imshow. I can achieve the colorbar that I want using the boundaries and values keywords, which makes the maximum value of the colorbar effectively 1 greater than the maximum value of the data being plotted.

Now I want ticks to be in the middle of each color range in the colorbar, but cannot specify a tick position for the largest color block in the colorbar, seemingly because it is outside of the data value limits.

Here's a quick block of code to demonstrate the problem:

data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
ax.imshow(data[None], aspect='auto')
cax = fig.add_subplot(122)
cbar = fig.colorbar(ax.images[0], cax=cax, boundaries=[0,1,2,3,4], values=[0,1,2,3])
cbar.set_ticks([.5, 1.5, 2.5, 3.5])
cbar.set_ticklabels(['one', 'two', 'three', 'four'])

Note the missing tick where 'four' should be. What's the right way to do this?

Answer

To summarize, this works for me:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import colorsdata = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
cmap = cm.get_cmap('jet', 4)
bounds = np.arange(5)
vals = bounds[:-1]
norm = colors.BoundaryNorm(bounds, cmap.N)
ax.imshow(data[None], aspect='auto', interpolation='nearest', cmap=cmap, norm=norm)cax = fig.add_subplot(122)
cbar = fig.colorbar(ax.images[0], cax=cax, boundaries=bounds, values=vals)
cbar.set_ticks(vals + .5)
cbar.set_ticklabels(['one', 'two', 'three', 'four'])

The solution was to specify the colormap explicitly for the image using get_cmap and bounded by BoundaryNorm. Then specifying the tick positions just works. The resulting plot is:

discrete colorbar example

https://en.xdnf.cn/q/69673.html

Related Q&A

Apache Airflow - customize logging format

Is it possible to customize the format that Airflow uses for logging?I tried adding a LOG_FORMAT variable in $AIRFLOW_HOME/airflow.cfg, but it doesnt seem to take effectLOG_FORMAT = "%(asctime)s …

How can I set up Celery to call a custom worker initialization?

I am quite new to Celery and I have been trying to setup a project with 2 separate queues (one to calculate and the other to execute). So far, so good. My problem is that the workers in the execute que…

Why does print(__name__) give builtins?

Im using pycharm.2017.1.2. I installed anaconda2 with py3 environment. in Pycharm, Im using Python3 interpreter, and the code is simply:print(__name__)In Python console in Pycharm, it prints builtins.I…

List Comprehensions and Conditions?

I am trying to see if I can make this code better using list comprehensions. Lets say that I have the following lists:a_list = [HELLO,FOO,FO1BAR,ROOBAR,SHOEBAR]regex_list = [lambda x: re.search(rFOO,…

Python in operator time complexity on range()

I have the following function:def foo(length, num):return num in range(length)Whats the time complexity of this function? Noting that range() creates a Range object on Python 3, will the time complexi…

Pandas read data from a secure FTP server in Python 3

I am looking for a neat solution to read data (using either read_csv or read_sas) to a Pandas Dataframe from a secure FTP server in Python 3. All the examples I can find are many lines and some for Pyt…

How to read XML header in Python

How can I read the header of an XML document in Python 3?Ideally, I would use the defusedxml module as the documentation states that its safer, but at this point (after hours of trying to figure this …

Shift interpolation does not give expected behaviour

When using scipy.ndimage.interpolation.shift to shift a numpy data array along one axis with periodic boundary treatment (mode = wrap), I get an unexpected behavior. The routine tries to force the firs…

HEX decoding in Python 3.2

In Python 2.x Im able to do this:>>> 4f6c6567.decode(hex_codec) OlegBut in Python 3.2 I encounter this error:>>> b4f6c6567.decode(hex_codec) Traceback (most recent call last):File &qu…

How do I access session data in Jinja2 templates (Bottle framework on app engine)?

Im running the micro framework Bottle on Google App Engine. Im using Jinja2 for my templates. And Im using Beaker to handle the sessions. Im still a pretty big Python newbie and am pretty stoked I g…