使用 Matplotlib 刷新我的饼图



我有一个使用matplotlib绘制的饼图。除了这个饼图,我还有一个滑块,按下它时会调用处理程序。我希望这个处理程序更改饼图的值。因此,例如,如果饼图分别具有 60% 和 40% 的标签,我希望在按下滑块时将标签修改为 90% 和 10%。这是代码:

这将绘制饼图和滑块:

plt.axis('equal');
explode = (0, 0, 0.1);
plt.pie(sizes, explode=explode, labels=underlyingPie, colors=colorOption,
        autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
a0 = 5;
axcolor = 'lightgoldenrodyellow'
aRisk  = axes([0.15, 0, 0.65, 0.03], axisbg=axcolor)
risk = Slider(aRisk, 'Risk', 0.1, 100.0, valinit=a0)
risk.on_changed(update);

以下是事件处理程序,所需的功能是修改标签并重绘饼图

def update(val):
    riskPercent = risk.val;
    underlyingPie[0] = 10;
    underlyingPie[1] = 90;
    plt.pie(sizes, explode=explode, labels=lab, colors=colorOption,
        autopct='%1.1f%%', shadow=True, startangle=90)

我也在绘制以下内容,我可以在同一画布上同时获得饼图和下面的图表吗?

fig = plt.figure();
ax1 = fig.add_subplot(211);
for x,y  in zip(theListDates,theListReturns):
    ax1.plot(x,y);
plt.legend("title");
plt.ylabel("Y axis");
plt.xlabel("X axis");
plt.title("my graph");

提前致谢

这应该是你要找的。您需要为饼图提供一个轴控点,以便不断对其进行修改。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
x = [50, 50]
fig, axarr = plt.subplots(3)
# draw the initial pie chart
axarr[0].pie(x,autopct='%1.1f%%')
axarr[0].set_position([0.25,0.4,.5,.5])
# create the slider
axarr[1].set_position([0.1, 0.35, 0.8, 0.03])
risk = Slider(axarr[1], 'Risk', 0.1, 100.0, valinit=x[0])
# create some other random plot below the slider
axarr[2].plot(np.random.rand(10))
axarr[2].set_position([0.1,0.1,.8,.2])
def update(val):
    axarr[0].clear()
    axarr[0].pie([val, 100-val],autopct='%1.1f%%')
    fig.canvas.draw_idle()
risk.on_changed(update)
plt.show()

最新更新