2013-10-22 47 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