2014-09-23 58 views
0

我見過幾個例子,但情節構造不同,我不明白如何使語法工作。這是我的代碼:如何在matplotlib中的x軸上縮小繪圖?

pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf") 
for i in range(0, len(list_of_data)): 
    biorep = int(list_of_figure_key[i].split('.')[1]) 
    construct = int(list_of_figure_key[i].split('.')[0].split('_')[1]) 
    plot(time, list_of_data[i], color=color_dict[construct], linestyle=linestyle_dict[biorep], label=list_of_figure_key[i]) 
    xlabel('time (hours)', fontsize=9) 
    ylabel(ReadType, fontsize=9) 
    xlim(min(time),max(time)) 
    legend(fontsize=8, loc='center left', bbox_to_anchor=(1, .5)) 
pdf_file.savefig() 

它產生了一個美麗的身影,但圖例太長,並且離開頁面的邊緣。我想縮小x軸上的圖形,以便圖例適合作爲2列的圖例。

圖可以在這裏看到:提前http://i.imgur.com/mvgzIhj.jpg

謝謝!

+0

回答你的問題Python標準縮進是四個空格而不是兩個 – Ajean 2014-09-24 15:49:55

回答

1

您可以使用ncol圖例屬性製作一個雙列圖例。您可以通過繪製在圖上軸和固定它的尺寸縮小的情節寬度:

from matplotlib import pyplot as plt 
fig = plt.figure()      # initialize figure 
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # add axis 

爲了讓你的代碼這項工作中,這樣的事情應該工作:

# import pyplot 
from matplotlib import pyplot as plt 

# set up filename to save it 
pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf") 

# set up axis object 
fig = plt.figure() 
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 

# plot your data 
for i in range(0, len(list_of_data)): 
    biorep = int(list_of_figure_key[i].split('.')[1]) 
    construct = int(list_of_figure_key[i].split('.')[0].split('_')[1]) 
    ax.plot(time, list_of_data[i], color=color_dict[construct], 
     linestyle=linestyle_dict[biorep], label=list_of_figure_key[i]) 

# modify axis limits and legend 
ax.set_xlabel('time (hours)', fontsize=9) 
ax.set_ylabel(ReadType, fontsize=9) 
ax.set_xlim(min(time),max(time)) 
ax.legend(fontsize=8, loc='upper left', bbox_to_anchor=(1, .5), ncol=2) 

# save final figure 
plt.savefig(pdf_file) 

在你代碼,您在for循環的每次迭代中都重新制作了圖例,限制和圖例,並保存並覆蓋了pdf圖像。這不是必需的 - 你可以在最後做一次。

欲瞭解更多的傳奇祕訣,this post是方便。 This one也有幫助。

+0

我的縮進有什麼問題? – user1539097 2014-09-24 02:58:10

+0

@Ajean我編輯了回覆以解決您提到的問題 - 讓我知道是否還有其他任何您認爲會改進的問題! – rebeccaroisin 2014-09-24 12:09:17

+0

@rebeccaroisin你是如此accomadating,愛它!有你的upvote爲你的麻煩 – Ajean 2014-09-24 14:12:19