如何解决“'PathCollection'对象没有属性'yaxis'”错误?

时间:2019-12-21 23:25:09

标签: python matplotlib visual-studio-code

我是一名MSc学生,我曾经使用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()

并且终端显示此错误:

enter image description here

  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'

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

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

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