【问题标题】:How to solve " 'PathCollection' object has no attribute 'yaxis' " error?如何解决“'PathCollection'对象没有属性'yaxis'”错误?
【发布时间】:2019-12-21 23:25:09
【问题描述】:

我是一名理学硕士学生,我曾经使用 OriginPro、Excel 和 Matlab 等商业软件包制作图形和绘图。尽管这些软件提供了出色的用户体验,但也存在一些主要缺点,因为它们依赖于特定的操作系统,而且通常非常昂贵。

因此,我开始使用带有 VS Code 的 matplotlib 库来学习 Python,但是我在一些库函数和语句方面遇到了一些问题,这些库函数和语句似乎是 matplotlib 和 numPy 的标准,但它不起作用。

例如,我正在为散点图制作一些模板,但我无法控制小刻度,因为它无法识别语句 xaxixyaxix

代码示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator

.
.
.

fig = plt.figure(figsize=(x_pixels/my_dpi, y_pixels/my_dpi), dpi=my_dpi)
ax = plt.scatter(x*format_x, y*format_y, s = size, alpha = transparency, color = color, label = legend_text)

.
.
.

# Major Ticks
plt.tick_params(axis = 'both', which = 'major', length = majorT_length, direction = majorT_direction, color = majorT_color, labelsize = label_size, top = 'on', right = 'on')

# Minor Ticks
plt.minorticks_on()
plt.tick_params(axis='both', which='minor', length = minorT_length, direction = minorT_direction, color = minorT_color, top = 'on', right = 'on')
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))

# Figure Layout
plt.tight_layout()
plt.savefig(output_file, dpi=my_dpi, bbox_inches=borders)

plt.show()

终端显示此错误:

  File "c:/Users/luagu/Desktop/Python Matplotlib Training/Scatter_Template.py", line 128, in <module>
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))
AttributeError: 'PathCollection' object has no attribute 'yaxis'

我做错了什么?

提前致谢!

【问题讨论】:

  • 请直接包含错误信息,不要作为图像。

标签: python matplotlib visual-studio-code


【解决方案1】:

您写了ax = plt.scatter,但您的axscatter 方法返回的艺术家,而不是Axes 对象。你想做的是:

plt.scatter(...)
...
ax = plt.gca()
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))

【讨论】:

  • 哦,它现在可以工作了!实际上这是有道理的,因为首先您需要通过 plt.gca() 获取轴,然后使用该命令。谢谢! :)
猜你喜欢
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2019-09-08
  • 2020-10-25
  • 2020-02-09
相关资源
最近更新 更多