python-'str' abject 没有属性 'scatter'

python-'str' abject has no attribute 'scatter'

我需要通过 metplotlib.pyplot 绘制一个 7x7 散点图(此时没有 seaborn)。我试图让它成为半自动的,所以我使用一个斧头名称 ax11、ax12、......、ax77 的数组来呈现子图。意思是当我使用它们调用 scatter 时,它被拒绝了,我认为 python 将它们识别为字符串而不是子图的关键字。错误消息是 "AttributeError: 'str' object has no attribute '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()

我相信有一种方法可以将字符串转换为正确的格式,但我不知道如何操作。请帮忙。谢谢

一般来说,应该避免使用字符串构建变量名的方法。虽然这可以使用 eval 函数来完成,但这甚至不是必需的。

问题出在行

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

字符串没有 scatter 方法。您需要的是要绘制的 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()