[英]how to change pcolor one grid color on click in matplotlib?
i'm new to python and matplotlib, i want to change grid color on click, but following code can't, how to do it?我是 python 和 matplotlib 的新手,我想在点击时更改网格颜色,但是下面的代码不能,怎么办? 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()
There are a few issues:有几个问题:
Z[_gy, _gx] = 25
要寻址 numpy 数组中的单元格,您需要逗号符号: Z[_gy, _gx] = 25
ax.pcolor
inside the onclick function would continuously create new colormeshes, one on top of the other until the system gets really slow;在 onclick function 中调用ax.pcolor
将不断创建新的颜色网格,一个在另一个之上,直到系统变得非常慢; usually a property of the already created element is updated;通常更新已创建元素的属性; mesh.set_array
is a way to update the values for the colors mesh.set_array
是一种更新 colors 值的方法ax.pcolor
, setting vmin
and vmax
tells matplotlib which value correspond to the lowest and which to the highest color;调用ax.pcolor
时,设置vmin
和vmax
会告诉 matplotlib 哪个值对应于最低颜色,哪个对应于最高颜色; it may also help to explicitly set a colormap (default it would be 'viridis')它也可能有助于显式 设置颜色图(默认为“viridis”)fig.canvas.draw()
may be needed to show the modified mesh (this depends on the environment in which matplotlib is run)可能需要fig.canvas.draw()
来显示修改后的网格(这取决于运行 matplotlib 的环境)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()
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.请注意, Z = np.random.rand(25, 25)
创建的值介于 0 和 1 之间。使用vmax=25
这会为背景设置一些随机的非常暗的 colors。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.