【问题标题】:Using setp to hide axes spines使用 setp 隐藏轴刺
【发布时间】:2020-08-13 08:49:44
【问题描述】:

我试图在matplotlib 中使用setp 将刺的可见性设置为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


    【解决方案1】:

    axes.spines 是一个OrderedDict。当您像这样迭代 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
    

    【讨论】:

    • 非常感谢!不仅是为了答案,而且是为了清晰的解释。这就是我想象的答案应该是:实用并提供很多见解。 (顺便说一句,作为你的名字 Axe319,你一定是个“斧头”专家;))
    【解决方案2】:

    我将发布我绝望的解决方案,仅供记录,如果它可能对某人有所帮助。虽然@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_visible(False) 一样一次隐藏所有轴,但之后命令axes.spines[spine_name].set_visible(True) 不起作用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 2011-05-04
      • 1970-01-01
      • 2022-08-08
      • 2013-02-05
      相关资源
      最近更新 更多