2016-05-31 94 views
1

如果我要設置x,軸系Y的標籤,我必須做這樣的事情:Matplotlib:在一行中設置x和y標籤

import matplotlib.pyplot as plt 
plt.plot([1,2,3,4]) 
plt.ylabel('This is y label') 
plt.xlabel('This is x label') 
plt.show() 

我需要設置xlabelylabel seperately。

我不知道是否有任何語法sugur,我可以這樣做:

plt.label('x label', 'y label') 

,使代碼看起來更緊湊?

或者我如何使任何自定義函數來做到這一點?

+1

你的代碼(或者你)是否真的患上了這兩行? – Chiel

回答

4

一旦你開始使用matplotlib面向對象模型更多的時候,你就可以到軸的所有相關參數作爲關鍵字添加到使這些功能軸。

一個簡單的例子:

fig = plt.figure() 
ax = fig.add_subplot(111, xlabel="time", ylabel="money") 

較長的例子:

fig1 = plt.figure(figsize=(10,8)) 
ax1 = fig1.add_axes((0.1, 0.1, 0.8, 0.8), # full positional control 
    frameon=True,       # display frame boundary 
    aspect='equal',      # set aspect ratio upon creation 
    adjustable='box',      # what part of the axes can change to meet the aspect ratio requirement? 
    xticks=[0.1, 1.2, 10],     
    xlabel='voltage (V)', 
    xlim=(0.05, 10.05), 
    yticks=[0, 10], 
    ylabel='current (µA)', 
    ylim=(0, 2)) 

上接收到的意見之後,您還可以使用「屬性批處理器」 ax.set,這是的漂亮的小matplotlib便利功能。

plt.close('all') 
plt.plot([1,2,3], [4, 7, 1]) 
plt.gca().set(xlabel='x', ylabel='y') 
+0

除了啓動一個新的標籤之外,您還可以提供一個修改'ax'標籤值的例子嗎? – cqcn1991

+0

@ cqcn1991當然,請參閱更新。 –

+0

非常感謝。還有一個想法,你能給我一個文檔鏈接嗎?我也想把它和'legend'設置結合起來。 – cqcn1991

1

也許這可以幫助你

import matplotlib.pyplot as plt 

def grap_label(g, lx='',ly=''): 
    plt.xlabel(lx) 
    plt.ylabel(ly) 
    plt.show() 

grap_label(plt.plot([1,2,3,4]), 'This is x label','This is y label') 
+0

是的,我做了一個非常類似的功能,除了我設置'lx = None'作爲默認值。但我認爲將它設置爲空字符串更聰明。所以我不必做一個if語句來檢查它是否爲'None' – cqcn1991

+0

編寫使用'plt'的函數並不是一個好主意,你應該編寫取得軸對象的函數然後處理它們。 – tacaswell