matplotlib: How can you specify colour levels in a 2D historgram

2024/9/7 19:17:37

I would like to plot a 2D histogram that includes both positive and negative numbers. I have the following code which uses pcolormesh but I am unable to specify the color levels to force the white color to corresponds to zero (i.e., I want my colorbar to be symmetric around zero). I've also tried imshow.

I know you can specify colour levels in plt.contour and plt.contourf but I can't find a way to plot the 2D histogram using blocks.

Any advice would be greatly appreciated.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm as CMfig = plt.figure()# create an example histogram which is asymmetrical around zero
x = np.random.rand(400)
y = np.random.rand(400)    
Z, xedges, yedges = np.histogram2d(x, y, bins=10)   
Z = Z - 2.plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r)plt.colorbar()
plt.savefig('test.png')

enter image description here

Answer

Thanks to http://nbviewer.ipython.org/gist/pelson/5628989

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import from_levels_and_colorsx = np.random.rand(400)
y = np.random.rand(400)
Z, xedges, yedges = np.histogram2d(x, y, bins=10)
Z = Z - 2.
#  -1 0 3 6 9
cmap, norm = from_levels_and_colors([-1, 0, 3, 6, 9, 12], ['r', 'b', 'g', 'y', 'm']) # mention levels and colors here
plt.pcolormesh(xedges, yedges, Z, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()

enter image description here

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

Related Q&A

Strange behavior from HTTP authentication with suds SOAP library

I have a working python program that is fetching a large volume of data via SOAP using suds. The web service is implemented with a paging function such that I can grab nnn rows with each fetch call an…

Scipy/Numpy/scikits - calculating precision/recall scores based on two arrays

I fit a Logistic Regression Model and train the model based on training dataset using the following import scikits as sklearn from sklearn.linear_model import LogisticRegression lr = LogisticRegression…

Cant create test client during unit test of Flask app

I am trying to find out how to run a test on a function which grabs a variable value from session[user_id]. This is the specific test method:def test_myProfile_page(self):with app.test_client() as c:w…

My python installation is broken/corrupted. How do I fix it?

I followed these instructions on my RedHat Linux version 7 server (which originally just had Python 2.6.x installed):beginning of instructions install build toolssudo yum install make automake gcc gcc-…

Function that returns a tuple gives TypeError: NoneType object is not iterable

What does this error mean? Im trying to make a function that returns a tuple. Im sure im doing all wrong. Any help is appreciated.from random import randint A = randint(1,3) B = randint(1,3) def make_…

Error when plotting DataFrame containing NaN with Pandas 0.12.0 and Matplotlib 1.3.1 on Python 3.3.2

First of all, this question is not the same as this one.The problem Im having is that when I try to plot a DataFrame which contains a numpy NaN in one cell, I get an error:C:\>\Python33x86\python.ex…

Java method which can provide the same output as Python method for HMAC-SHA256 in Hex

I am now trying to encode the string using HMAC-SHA256 using Java. The encoded string required to match another set of encoded string generated by Python using hmac.new(mySecret, myPolicy, hashlib.sha2…

How to get response from scrapy.Request without callback?

I want to send a request and wait for a response from the server in order to perform action-dependent actions. I write the followingresp = yield scrapy.Request(*kwargs)and got None in resp. In document…

install error thinks pythonpath is empty

I am trying to install the scikits.nufft package here I download the zip file, unpack and cd to the directory. It contains a setup.py file so I run python setup.py installbut it gives me the following …

Conditionally installing importlib on python2.6

I have a python library that has a dependency on importlib. importlib is in the standard library in Python 2.7, but is a third-party package for older pythons. I typically keep my dependencies in a pip…