使用setp隐藏轴刺

问题描述 投票:0回答:2

我正在尝试使用setp中的matplotlib来设置刺的可见性为False,但出现错误“ AttributeError: 'str' object has no attribute 'update'”。据我了解,使用setp我们可以更改可迭代对象的属性,并希望使用spines执行它。

有效使用setp的正确语法是什么?

他的MWE:

import matplotlib.pyplot as plt

x = range(0,10)
y = [i*i for i in x]

plt.plot(x,y) #Plotting x against y
axes = plt.gca() #Getting the current axis

axes.spines['top'].set_visible(False) #It works

plt.setp(axes.spines, visible=False) #It rises error

plt.show() #Showing the plot

版本: python3.8.2,Matplotlib 3.2.1

python-3.x matplotlib plot axes
2个回答
1
投票

axes.spinesOrderedDict。当您像这样遍历DictOrderedDict时:

for key in axes.spines:
    print(type(key))

您正在迭代键,这些键是字符串,没有更新方法。 Here您可以通过仅传入可迭代对象或对象来查看可以使用plt.setp()设置哪些参数。

plt.setp(axes.spines)

这将返回None,因为它引用了键,这些键是字符串,没有更新方法。按照这种逻辑,如果我们尝试这样做:

plt.setp(axes.spines.values())

我们看到这确实返回了可能的参数。因此,总而言之,将plt.setp(axes.spines, visible=False)更改为plt.setp(axes.spines.values(), visible=False)将删除所有刺,因为它遍历对象而不是键。

完整代码:

import matplotlib.pyplot as plt

x = range(0,10)
y = [i*i for i in x]

plt.plot(x,y) #Plotting x against y
axes = plt.gca() #Getting the current axis

axes.spines['top'].set_visible(False)

plt.setp(axes.spines.values(), visible=False) 

plt.show() #Showing the plot

0
投票

我将发布自己急切的解决方案,仅作记录,以帮助他人。尽管@ axe319的答案几乎不容小ump。

© www.soinside.com 2019 - 2024. All rights reserved.