Update range of colorbar in matplotlib

2024/10/8 2:20:30

I want to update a contourf plot within a function, which works fine. However, the range of the data changes and I therefore also have to update the colorbar. That is where I fail to do so.

Please see following minimum working example:

import matplotlib.pyplot as plt
import numpy as npfig = plt.figure()
ax = fig.add_subplot(111)# Random data
data = np.random.rand(10, 10)# Plot data
levels = np.linspace(0., 1., 100)
plot = ax.contourf(data, levels=levels)
clist = plot.collections[:]# Create colorbar
cbar = plt.colorbar(plot)
cbar_ticks = np.linspace(0., 1., num=6, endpoint=True)
cbar.set_ticks(cbar_ticks)plt.show()def update():# Remove old plotfor c in clist:ax.collections.remove(c)clist.remove(c)# Create new data and plotnew_data   = 2.*np.random.rand(10, 10)new_levels = np.linspace(0., 2., 200)new_plot = ax.contourf(new_data, levels=new_levels )# Modify colorbarcbar.set_clim(0., 2.)new_cbar_ticks = np.linspace(0., 2., num=21, endpoint=True)cbar.set_ticks(new_cbar_ticks)plt.draw()update()

Without calling update() I get the following image:

enter image description here

This is exactly what I want. In the update() function I basically change the range of the data from [0,1) to [0,2), create new data, and update the plot. I also tried to double the sampling in the colorbar ticks to have ticks in an interval of 0.1, instead of 0.2. This is what I get:

enter image description here

The data is correctly plotted, the colormap of the data is correct, the ticks and the color in the colorbar are correct, but the range of the colorbar is still from 0 to 1. How can I change the colorbar to show the full range up to 2?

Answer

Can you work with imshow instead of contour? In that case it is easy to just update both, the plot and the colorbar.

import matplotlib.pyplot as plt
import numpy as npfig = plt.figure()
ax = fig.add_subplot(111)# Random data
data = np.random.rand(10, 10)# Plot data
plot = ax.imshow(data)# Create colorbar
cbar = plt.colorbar(plot)
cbar_ticks = np.linspace(0., 1., num=6, endpoint=True)
cbar.set_ticks(cbar_ticks)plt.show(block=False)def update():new_data   = 2.*np.random.rand(10, 10)plot.set_data(new_data)cbar.set_clim(vmin=0,vmax=2)cbar_ticks = np.linspace(0., 2., num=11, endpoint=True)cbar.set_ticks(cbar_ticks) cbar.draw_all() plt.draw()plt.show()update()
https://en.xdnf.cn/q/70172.html

Related Q&A

Anaconda - arrow keys not work well in python shell

I installed Anaconda3 on manjaro (with i3wm and Urxvt). When I go into python interpreter, it is OK to type python script and execute. But when key arrows are pressed to call up history, everything mes…

couldnt remove origin point in matplotlib polycollection

I have tried an example with PolyCollection from matplotlib tutorials and noticed one strange thing. I couldnt remove this points from axes origin see fig. How do I manage this?from mpl_toolkits.mplot…

How to read .odt using Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.The com…

Modifying Django settings in tests

From Django docs:You shouldn’t alter settings in your applications at runtime. Forexample, don’t do this in a view:from django.conf import settingssettings.DEBUG = True # Dont do this!The only plac…

How To Use Django Cycle Tag

This hopefully is a pretty easy question. My endgoal is to be able to view my database entries in a table which I can sort via the column headers. I have read the documentation on cycle tags, but dont …

Multiple linear regression with python

I would like to calculate multiple linear regression with python. I found this code for simple linear regressionimport numpy as npfrom matplotlib.pyplot import *x = np.array([1, 2, 3, 4, 5])y = np.arra…

How to find source of error in Python Pickle on massive object

Ive taken over somebodys code for a fairly large project. Im trying to save program state, and theres one massive object which stores pretty much all the other objects. Im trying to pickle this object,…

What is the most idiomatic way to index an object with a boolean array in pandas?

I am particularly talking about Pandas version 0.11 as I am busy replacing my uses of .ix with either .loc or .iloc. I like the fact that differentiating between .loc and .iloc communicates whether I a…

Error: Command failed with rc=65536 python and mod_wsgi

im having this problem: im runing pythonbrew to get python2.7, and so i re-compiled mod_wsgi to use the 2.7 python. to that end, i followed this tutorial: code.google.com/p/modwsgi/wiki/QuickInstallati…

Why cant I freeze_panes on the xlsxwriter object pandas is creating for me?

I have a class whose objects contain pandas dataframes (self.before, and self.after below) and a save() method which uses xlsxwriter to export the data (which has two worksheets, "before" and…