鼠标悬停事件发生时如何更改饼图切片的颜色

时间:2017-09-01 12:47:47

标签: python matplotlib

我在matplotlib创建了一个饼图。我想在python 中实现this结果。每当鼠标悬停在任何切片上时,它的颜色都会改变。我已经搜索了很多并且想出了使用bind方法但是这样做并没有效果,因此无法提出积极的结果。如果可以通过任何其他库(例如tkinterplotly等)完成此操作,我将毫无疑问,但我需要使用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()

...问候

2 个答案:

答案 0 :(得分:3)

motion_notify_event需要matplotlib event handler。 这可以连接到一个函数,该函数检查鼠标是否在饼图的一个楔形内。这是通过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()

答案 1 :(得分:0)

首先,你要找的是the documentation on Event handling in matplotlib。特别是,每次鼠标移动时都会触发var comboBoxItem = sexCombo.Items.OfType<ComboBoxItem>().FirstOrDefault(x => x.Content.ToString() == teacherInfo["sex"].ToString()); int index = sexCombo.SelectedIndex = sexCombo.Items.IndexOf(comboBoxItem); 。但是,我想不出一个简单的方法来确定鼠标现在在哪个楔形物上。

如果点击是可以接受的,那么问题就容易多了:

motion_notify_event
相关问题