【问题标题】:python-'str' abject has no attribute 'scatter'python-'str' 对象没有属性'scatter'
【发布时间】:2017-06-04 10:46:55
【问题描述】:

我需要通过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()

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

【问题讨论】:

  • 目前尚不清楚您要使用此代码实现什么目标。主要原因是没有人知道data 是什么。您需要提供该信息,最好直接在您的代码中包含data。使用允许重现错误的简化版本。
  • 可能与数据类型无关。问题是平时使用ax1.scatter([1,2,3],[1,2,3])的时候,这里我使用'ax11'.scatter([1,2,3],[1,2 ,3])。字符串 'ax11' 需要转换为与 ax1 相同的类型。我猜这就是 Python 的发展方式。
  • 它与数据类型无关。正如你上面所说,"ax"+str(no_ax) 是一个 python 字符串,但你需要 Axes 实例来调用 scatter 。有很多方法可以遍历这些轴实例;查看matplotlib 示例以了解一些情况。例如,matplotlib.org/examples/pylab_examples/subplots_demo.html

标签: string python-3.x matplotlib scatter-plot subplot


【解决方案1】:

一般而言,应避免使用从字符串构建变量名称的方法。虽然这可以使用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()

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 2022-01-21
    • 2018-12-01
    • 2015-09-30
    • 2021-10-22
    • 2020-09-22
    • 2020-06-25
    • 2016-12-27
    • 2015-03-08
    相关资源
    最近更新 更多