2017-01-19 4 views
-1

metplotlib.pyplot(この時点では海底はありません)によって7x7散布図をプロットする必要があります。私はそれをセミオートマトンにしようとしていますので、ax11、ax12、......、ax77の配列を使ってサブプロットを表示します。 Pythonはそれらを文字列として認識しますが、サブプロットのキーワードではないと考えています。エラーメッセージは "AttributeError: 'str'オブジェクトには 'scatter'属性がありません。ここでは、コードの一部である:python-'str 'abjectには' scatter 'という属性はありません


import matplotlib.pyplot as plt 
import numpy as np 

characters = ['A','B','C','D','E','F'] 

box = dict(facecolor ='yellow', pad = 5, alpha = 0.2) 

fig, ((ax11,ax12,ax13,ax14,ax15,ax16,ax17),\ 
     (ax21,ax22,ax23,ax24,ax25,ax26,ax27),\ 
     (ax31,ax32,ax33,ax34,ax35,ax36,ax37),\ 
     (ax41,ax42,ax43,ax44,ax45,ax46,ax47),\ 
     (ax51,ax52,ax53,ax54,ax55,ax56,ax57),\ 
     (ax61,ax62,ax63,ax64,ax65,ax66,ax67),\ 
     (ax71,ax72,ax73,ax74,ax75,ax76,ax77),\ 
    ) = plt.subplots(7,7) 
fig.subplots_adjust(left = 0.2, wspace =0.2,) 
fig.tight_layout(pad=1, w_pad=2, h_pad=4.0) 
st = fig.suptitle("Scatterplot diagram", \ 
    fontsize="x-  large") 

for i in range(7): 
    for j in range(7): 
     no_ax = str(i)+str(j) 
     nm_ax = "ax"+str(no_ax) 
     nm_ax.scatter(data[caracters[i]],data[caracters[i]]) 
     nm_ax.set_title('xy') 
     nm_ax.set_xlabel('x') 
     nm_ax.set_ylabel('y') 
     continue 

st.set_y(0.95) 
fig.subplots_adjust(top=0.85) 

plt.show() 

私は適切なフォーマットに文字列を変換する方法があると信じているが、私は方法がわかりません。助けてください。ありがとう。

+0

このコードで達成しようとしていることは不明です。主な理由は誰も「データ」が何であるかを知っていないということです。あなたはその情報を提供する必要があり、あなたのコードに 'data'を直接入れる方が良いでしょう。エラーを再現できる単純化されたバージョンを使用してください。 – ImportanceOfBeingErnest

+0

データ型と何も関係がない可能性があります。問題は、通常ax1.scatter([1,2,3]、[1,2,3])を使用するときですが、ここで私は 'ax11'.scatter([1,2,3]、[1,2 、3])。文字列 'ax11'はax1と同じ型に変換する必要があります。これがPythonのやり方です。 – yuewu008

+0

そのデータ型とは関係ありません。上記のように、 '' ax "+ str(no_ax)'はPython文字列ですが、 'scatter'を呼び出すには' Axes'インスタンスが必要です。これらのAxesインスタンスをループする方法はたくさんあります。 'matplotlib'の例を見てみましょう。たとえば、http://matplotlib.org/examples/pylab_examples/subplots_demo.html – tom

答えて

0

一般に、文字列から変数名を作成するアプローチは避けるべきです。これはeval関数を使用して行うことができますが、それは必要でもありません。

問題は、文字列がscatterメソッドを持っていない

no_ax = str(i)+str(j) #this is a string 
nm_ax = "ax"+str(no_ax) # this is still a string 
nm_ax.scatter(data[caracters[i]],data[caracters[i]]) 
# a string cannot be plotted to 

ラインです。必要なのは、プロットするオブジェクトのaxesです。

解決策は、ループ内で直接plt.subplots()の呼び出しで作成された軸をそのまま使用することです。

import matplotlib.pyplot as plt 
import numpy as np 

fig, axes = plt.subplots(ncols=7,nrows=7) 

for i in range(7): 
    for j in range(7): 
     axes[i,j].scatter(np.random.rand(5),np.random.rand(5)) 
     axes[i,j].set_title('{},{}'.format(i,j)) 

plt.show() 
関連する問題