我正在使用matplotlib,我正在尝试在选择时更改标记的颜色。到目前为止,我正在绘制标记并添加一个调用pick_event
函数的on_pick
侦听器,然后修改情节的标记属性。这不起作用,因为我无法弄清楚如何访问标记的属性。我该怎么做?
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
#-----------------------------------------------
# Plots several points with cubic interpolation
#-----------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 10, num=6, endpoint=True)
y = abs(x**2)
xnew = np.linspace(0, 10, num=40, endpoint=True)
cubicInterp = interp1d(x, y, kind='cubic')
line, = ax.plot(x,y, 'o', picker=5) # 5 points tolerance
lineInterp = ax.plot(xnew,cubicInterp(xnew), '-')
#---------------
# Events
#---------------
def on_pick(event):
line.color='red'
thisline.color='red'
#-----------------------------
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
答案 0 :(得分:1)
这不起作用,因为我没有使用plt.show()更新绘图并使用了错误的getter方法。这是正确的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
#-----------------------------------------------
# Plots several points with cubic interpolation
#-----------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 10, num=6, endpoint=True)
y = abs(x**2)
xnew = np.linspace(0, 10, num=40, endpoint=True)
cubicInterp = interp1d(x, y, kind='cubic')
line, = ax.plot(x,y, 'o', picker=5) # 5 points tolerance
lineInterp = ax.plot(xnew,cubicInterp(xnew), '-')
#---------------
# Events
#---------------
def on_pick(event):
thisline = event.artist
thisline.set_markerfacecolor("red")
plt.show()
#-----------------------------
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
答案 1 :(得分:1)
您可以使用setp方法操作绘图元素并更新cavas。这有效:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
#-----------------------------------------------
# Plots several points with cubic interpolation
#-----------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 10, num=6, endpoint=True)
y = abs(x**2)
xnew = np.linspace(0, 10, num=40, endpoint=True)
cubicInterp = interp1d(x, y, kind='cubic')
line = ax.plot(x,y, 'o', picker=5) # 5 points tolerance
lineInterp = ax.plot(xnew,cubicInterp(xnew), '-')
#---------------
# Events
#---------------
def on_pick(event):
print "clicked"
plt.setp(line,'color','red')
fig.canvas.draw()
#-----------------------------
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()