我在 matplotlib
创建了一个饼图。我想实现this结果是 python ,即每当鼠标悬停在任何切片上时,其颜色就会改变。我进行了大量搜索并想出了 bind
的使用但这种方法并不有效,因此无法得出积极的结果。如果可以通过任何其他库来完成此操作(例如 tkinter
、 plotly
等,但我需要用 matplotlib
提出解决方案,所以我会更感激)。请看一下通过我的问题和任何建议都受到热烈欢迎......
这是我的代码:
import matplotlib.pyplot as plt
labels = 'A', 'B', 'C', 'D'
sizes = [10, 35, 50, 5]
explode = (0, 0, 0.1, 0) # only "explode" the 3rd slice (i.e. 'C')
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
问候...
最佳答案
您需要一个matplotlib event handler对于 motion_notify_event
。
这可以连接到一个函数,该函数检查鼠标是否位于饼图的楔形之一内。这是通过 contains_point
完成的。在这种情况下,请对楔形进行不同的着色,否则将其颜色设置为其原始颜色。
import matplotlib.pyplot as plt
labels = 'A', 'B', 'C', 'D'
sizes = [10, 35, 50, 5]
explode = (0, 0, 0.1, 0) # only "explode" the 3rd slice (i.e. 'C')
fig1, ax1 = plt.subplots()
wedges, _, __ = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ocols= [w.get_facecolor() for w in wedges]
ncols= ["gold", "indigo", "purple", "salmon"]
def update(event):
if event.inaxes == ax1:
for i, w in enumerate(wedges):
if w.contains_point([event.x, event.y]):
w.set_facecolor(ncols[i])
else:
w.set_facecolor(ocols[i])
fig1.canvas.draw_idle()
fig1.canvas.mpl_connect("motion_notify_event", update)
plt.show()
关于python - 如何在鼠标悬停事件发生时更改饼图切片的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000595/