0

i'm new to python and matplotlib, i want to change grid color on click, but following code can't, how to do it? enter image description here

#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
import math
     
Z = np.random.rand(25, 25)

Z = []
for x in range(25) :
    sublist = [1]*25
    Z.append(sublist)


fig, ax = plt.subplots()

Z[0][0] = 0
mesh = ax.pcolor(Z,edgecolor= 'k')

def onclick(event):
    print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          ('double' if event.dblclick else 'single', event.button,
           event.x, event.y, event.xdata, event.ydata))
    _gx = int(math.floor(event.xdata))
    _gy = int(math.floor(event.ydata))
    print("index x=%d y=%d", _gx,_gy)
    Z[_gy][_gx] = 25
    ax.pcolor(Z)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.title('matplotlib.pyplot.pcolormesh() function Example', fontweight ="bold")
plt.show()
GaoSam
  • 1

1 Answers1

0

There are a few issues:

  • numpy arrays and lists of lists are quite different concepts, although they both represent a 2D array of values. To address a cell in an numpy array, you need the comma notation: Z[_gy, _gx] = 25
  • for an interactive it helps to not constantly recreate the same graphical elements; calling ax.pcolor inside the onclick function would continuously create new colormeshes, one on top of the other until the system gets really slow; usually a property of the already created element is updated; mesh.set_array is a way to update the values for the colors
  • when calling ax.pcolor, setting vmin and vmax tells matplotlib which value correspond to the lowest and which to the highest color; it may also help to explicitly set a colormap (default it would be 'viridis')
  • fig.canvas.draw() may be needed to show the modified mesh (this depends on the environment in which matplotlib is run)
import matplotlib.pyplot as plt
import numpy as np
import math

def onclick(event):
    print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          ('double' if event.dblclick else 'single', event.button,
           event.x, event.y, event.xdata, event.ydata))
    _gx = int(math.floor(event.xdata))
    _gy = int(math.floor(event.ydata))
    print("index x=%d y=%d", _gx, _gy)
    Z[_gy, _gx] = 25
    mesh.set_array(Z.ravel())
    fig.canvas.draw()

Z = np.random.rand(25, 25)

fig, ax = plt.subplots()

mesh = ax.pcolor(Z, edgecolor='k', cmap='plasma', vmin=0, vmax=25)
fig.canvas.mpl_connect('button_press_event', onclick)

plt.title('matplotlib.pyplot.pcolormesh() function Example', fontweight="bold")
plt.show()

pcolor mesh with interactive update

Note that Z = np.random.rand(25, 25) creates values between 0 and 1. With vmax=25 this sets some random very dark colors for the background.

JohanC
  • 71,591
  • 8
  • 33
  • 66