Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib contourf: get Z value under cursor

When I plot something with contourf, I see at the bottom of the plot window the current x and y values under the mouse cursor. Is there a way to see also the z value?

Here an example contourf:

import matplotlib.pyplot as plt
import numpy as hp
plt.contourf(np.arange(16).reshape(-1,4))
like image 661
Andrea Zonca Avatar asked Apr 09 '12 23:04

Andrea Zonca


People also ask

What is the cursor widget of Matplotlib?

Some examples of widgets in matplotlib are Button, CheckButtons, RadioButtons, Cursor, and TextBox. In this article, the Cursor Widget of Matplotlib library has been discussed. A Cursor spans the axes horizontally and/or vertically and moves with the mouse cursor. Syntax: Cursor (ax, horizOn=True, vertOn=True, useblit=False, **lineprops)

Is it hard to make a contour plot in Python?

This isn’t to say Pythonic contour plots don’t come with their own set of frustrations, but hopefully this post will make the task easier for any of you going down this road. The most difficult part of using the Python/matplotlib implementation of contour plots is formatting your data.

How do you find the range of a contour?

If not given, they are assumed to be integer indices, i.e. X = range (N), Y = range (M). The height values over which the contour is drawn.

What is the difference between contourf and MATLAB?

If given, all parameters also accept a string s, which is interpreted as data [s] (unless this raises an exception). contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour.


2 Answers

The text that shows the position of the cursor is generated by ax.format_coord. You can override the method to also display a z-value. For instance,

import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as si
data = np.arange(16).reshape(-1, 4)
X, Y = np.mgrid[:data.shape[0], :data.shape[1]]
cs = plt.contourf(X, Y, data)

func = si.interp2d(X, Y, data)
def fmt(x, y):
    z = np.take(func(x, y), 0)
    return 'x={x:.5f}  y={y:.5f}  z={z:.5f}'.format(x=x, y=y, z=z)


plt.gca().format_coord = fmt
plt.show()
like image 117
wilywampa Avatar answered Nov 11 '22 11:11

wilywampa


The documentation example shows how you can insert z-value labels into your plot

Script: http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/contour_demo.py

Basically, it's

plt.figure()
CS = plt.contour(X, Y, Z) 
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')
like image 39
j13r Avatar answered Nov 11 '22 10:11

j13r