我想做一个matplotlib的图,其中的图例可以通过切换来选择可见性。 如果我点击某些图例,被点击的图例就会褪色,相应的图就会不可见。如果再次点击,它就会恢复到原来的状态。 但是下面的代码不能很好地工作。如果我点击图例'10'。这个动作可以被感应到,但是隐藏相关的图却不能工作。请给出一些建议。
import sys
import pandas as pd
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as canvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import matplotlib.colors as colors
import matplotlib.cm as cm
import numpy as np
class MplCanvas(canvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super().__init__(fig)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
df = pd.DataFrame({
"X" : [1,2,3,4,5],
"Y" : [1,2,3,4,5],
"pitch":[10,10,20,20,30],
layout_main = QVBoxLayout()
# define scatterplot
self.sc = MplCanvas(self, width=5, height=4, dpi=100)
color = cm.jet
u, div = np.unique(df.pitch.values, return_inverse=True)
colorlist = [colors.rgb2hex(color(i)) for i in np.linspace(1, 0, len(u))]
cmap = ListedColormap(colorlist)
self.scatter = self.sc.axes.scatter(df['X'], df['Y'] , c=div, cmap=cmap)
legend = self.sc.axes.legend(self.scatter.legend_elements(prop='colors', num=len(colorlist))[0], u, loc=2)
l1, l2, l3 = legend.get_lines()
l1.set_picker(True)
l1.set_pickradius(10)
self.scatter.figure.canvas.mpl_connect('pick_event', self.on_pick)
toolbar = NavigationToolbar(self.sc, self)
layout_main.addWidget(toolbar)
layout_main.addWidget(self.sc)
widget = QWidget()
widget.setLayout(layout_main)
self.setCentralWidget(widget)
def on_pick(self, event):
print('legend picked.')
picked_legend = event.artist
isVisible = picked_legend.get_visible()
self.scatter.picked_legend.set_visible(not isVisible)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()