【问题标题】:refresh my piechart using matplotlib?使用 matplotlib 刷新我的饼图?
【发布时间】:2013-10-22 17:56:05
【问题描述】:

我有一个使用 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");

提前致谢

【问题讨论】:

  • 那么问题是什么?
  • 在调用滑块时用新值重新绘制饼图
  • 我收集到了,但是您的代码看起来或多或少是正确的,什么不起作用?

标签: python python-2.7 python-3.x matplotlib


【解决方案1】:

这应该就是您要查找的内容。您需要有一个饼图的轴句柄才能继续对其进行修改。

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()

【讨论】:

  • 你好 aganders3,非常感谢您的回复,您的解决方案完美运行,唯一的补充是我在我想要饼图的同一画布上绘制另一个图表,我们有机会吗?我已经修改了上面的代码来说明
  • 如果您的需求发生重大变化,您应该打开另一个问题。但是,在同一个图中绘制另一个图应该没有问题。只需根据需要绘制的数量更改plt.subplots 参数即可。
  • 我有一个新问题,如果你能看一下,我将不胜感激 - 19545485/different-figures-on-different-canvases-using-matplotlib
猜你喜欢
  • 1970-01-01
  • 2017-07-13
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多