2017-09-03 12 views
0

プロットにタイトルやラベルを付けることについて質問があります。 私はこのようなシステムを使用することを好むほとんどの時間:しかし、今のところ、私はMatlabのスクリプトを変換し、できるだけ近いことが matplotlibの1つのプロットにタイトルやラベルを追加する正しい方法

import matplotlib.pyplot as plt 
x = [1,2,3,4] 
y = [20, 21, 20.5, 20.8] 

fig, axarr = plt.subplots(n,m) 
axarr[n,m] = plt.plot(x,y) 
axarr[n,m].set_xlabel('x label') 
axarr[n,m].set_ylabel('y label') 
axarr[n,m].set_xlabel('title') 
etc 

iはシステム、そのビットを試してみたいです。 私は私のコードは次のようなものを見なければならないことを期待する:

import matplotlib.pyplot as plt 
x = [1,2,3,4] 
y = [20, 21, 20.5, 20.8] 

ax = plt.plot(x,y) 
ax.set_xlabel('x label') 
ax.set_ylabel('y label') 
ax.set_xlabel('title') 
etc 

しかし、今のラベル/タイトル

AttributeError: 'list' object has no attribute 'set_xlabel'は、だから私は周りを探し、次のコードは、うまくいくhttps://sites.google.com/site/scigraphs/tutorial上で見つけたエラーを与えるが。

#import matplotlib libary 
import matplotlib.pyplot as plt 


#define some data 
x = [1,2,3,4] 
y = [20, 21, 20.5, 20.8] 

#plot data 
plt.plot(x, y, linestyle="dashed", marker="o", color="green") 

#configure X axes 
plt.xlim(0.5,4.5) 
plt.xticks([1,2,3,4]) 

#configure Y axes 
plt.ylim(19.8,21.2) 
plt.yticks([20, 21, 20.5, 20.8]) 

#labels 
plt.xlabel("this is X") 
plt.ylabel("this is Y") 

#title 
plt.title("Simple plot") 

#show plot 
plt.show() 

だから、基本的に、私はラベルやタイトルを追加するための中間の方法を使用することはできません(してくださいまた、なぜ)が、私は必要とするか、またはサブプロット(法1)または実施例の方法なぜ私の質問ですか?

答えて

1

the documentation for plot() explainsとして、plot()は、オブジェクトのリストを返します。Axesではなく、2番目のコードが機能しません。

  • はどちらかあなたがpyplot APIimport matplotlib.pyplot as plt)を使用します。

    は本質的には、matplotlibのを使用するための2つの方法があります。その後、各コマンドはplt.xxxxx()で始まり、最後に作成されたAxesオブジェクトで動作します。通常は明示的に参照する必要はありません。

あなたのコードは次のようになります。

plt.plot(x,y) 
plt.xlabel('x label') 
plt.ylabel('y label') 
plt.xlabel('title') 
  • あなたはあなたのコードが書き込まれる

オブジェクト指向のアプローチを使用するか:

fig, ax = plt.subplots() 
line, = ax.plot(x,y) 
ax.set_xlabel('x label') 
ax.set_ylabel('y label') 
ax.set_xlabel('title') 

それは、両方のアプローチを混在させることは通常推奨されません。 pyplot APIはMATLABから移行する人には便利ですが、いくつかのサブプロットでは、どのAxesが作業しているのかを確認するのが難しくなるため、オブジェクト指向のアプローチが推奨されます。

詳細については、this part of matplotlib FAQsを参照してください。

関連する問題