2013-10-22 45 views
1

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

此提请饼图和滑块:

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"); 

在此先感谢

+0

那么问题是什么? – tacaswell

+0

当滑块被调用时用新值重绘饼图 – godzilla

+0

我收集了这个,但你的代码看起来或多或少正确,什么是不工作? – tacaswell

回答

3

这应该是相当多,你在找什么。你需要有一个饼图的轴手柄,以便不断修改它。

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

hello aganders3,非常感谢您的回复,您的解决方案完美无瑕,唯一的补充是我在同一个画布上绘制了另一个图表,我想要这个图表,我们可以做到这一点吗?我已经修改了上面的代码来说明 – godzilla

+1

如果您的需求发生显着变化,您应该打开另一个问题。但是,在同一幅图中绘制另一个绘图应该没有问题。根据您需要绘制的数量,只需更改'plt.subplots'参数。 – aganders3

+0

查看我的编辑以解决您修改的问题。 – aganders3