Python 3.x 使用setp隐藏轴脊椎
我试图在Python 3.x 使用setp隐藏轴脊椎,python-3.x,matplotlib,plot,axes,Python 3.x,Matplotlib,Plot,Axes,我试图在matplotlib中使用setp将脊椎的可见性设置为False,但我得到错误“AttributeError:'str'对象没有属性“update””。 据我所知,使用setp我们可以更改iterable对象的属性,并希望使用spines执行它 有效使用setp的正确语法是什么 他说: import matplotlib.pyplot as plt x = range(0,10) y = [i*i for i in x] plt.plot(x,y) #Plotting x again
matplotlib
中使用setp
将脊椎的可见性设置为False
,但我得到错误“AttributeError:'str'对象没有属性“update”
”。
据我所知,使用setp
我们可以更改iterable对象的属性,并希望使用spines
执行它
有效使用setp的正确语法是什么
他说:
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
axes.spines
是一个OrderedDict
。当您在Dict
或orderedict
上迭代时,如下所示:
for key in axes.spines:
print(type(key))
您正在迭代键,这些键是字符串,没有更新方法。只需传入iterable或类似的对象,就可以看到可以使用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
我将发布我的绝望解决方案,只是为了记录在案,如果它可能帮助某人。尽管@axe319的答案很难被击败 我只需要重复一下脊椎的名字:
spine_names = ('top','right', 'bottom', 'left')
for spine_name in spine_names:
axes.spines[spine_name].set_visible(False)
它可以工作,但没有那么优雅和灵活,显然,它放弃了使用setp
:-\
警告:
有人可能会认为另一种解决方案是
axes.set_frame_on(False)
但是,一点也不。我试过了。虽然使用
set\u visible(False)
时它肯定会一次隐藏所有轴,但之后命令axes.spines[spine\u name].set\u visible(True)
不起作用 非常感谢!不仅是为了答案,也是为了清楚的解释。这就是我认为答案应该是:实用的,并提供大量的洞察力。(顺便说一下,您的名字是Axe319,您必须是“轴”专家;)