【问题标题】:Setting spines in matplotlibrc在 matplotlibrc 中设置脊椎
【发布时间】:2011-03-27 05:51:02
【问题描述】:

由于一个奇怪的原因,我找不到在 Python 的 matplotlibrc 文件中指定脊椎配置的方法。关于如何使matplotlib默认不绘制上下脊椎的任何想法?
(来源:sourceforge.net

更多关于 matplotlib 中脊椎的信息是here

谢谢

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    为了隐藏子图的右侧和顶部刺,您需要将相关刺的颜色设置为'none',并将刻度位置设置为'left'(用于xtick)和@987654323 @ 表示 ytick(为了隐藏刻度线和刺)。

    很遗憾,目前这些都无法通过matplotlibrc 访问。在matplotlibrc 中指定的参数经过验证,然后存储在一个名为rcParams 的字典中。然后由各个模块检查此字典中的键,其值将作为其默认值。如果他们不检查其中一个选项,则该选项无法通过rc 文件更改。

    由于rc 系统的性质以及脊椎的编写方式,修改代码以实现这一点并不简单:

    Spines 当前通过用于定义轴颜色的相同rc 参数获取它们的颜色;如果不隐藏所有轴图,则无法将其设置为 'none'。他们也不知道他们是toprightleft,还是bottom——这些实际上只是存储在一个字典中的四个独立的刺。各个脊椎对象不知道它们构成绘图的哪一侧,因此您不能只添加新的rc 参数并在脊椎初始化期间分配正确的参数。

    self.set_edgecolor( rcParams['axes.edgecolor'] )
    

    (./matplotlib/lib/matplotlib/spines.py, __init__(), 第 54 行)

    如果您有大量现有代码,例如手动将轴参数添加到每个参数将过于繁琐,您可以交替使用辅助函数来遍历所有 Axis 对象并为您设置值。

    这是一个例子:

    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.pyplot import show
    
    # Set up a default, sample figure. 
    fig = plt.figure()
    x = np.linspace(-np.pi,np.pi,100)
    y = 2*np.sin(x)
    
    ax = fig.add_subplot(1,2,2)
    ax.plot(x,y)
    ax.set_title('Normal Spines')
    
    def hide_spines():
        """Hides the top and rightmost axis spines from view for all active
        figures and their respective axes."""
    
        # Retrieve a list of all current figures.
        figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
        for figure in figures:
            # Get all Axis instances related to the figure.
            for ax in figure.canvas.figure.get_axes():
                # Disable spines.
                ax.spines['right'].set_color('none')
                ax.spines['top'].set_color('none')
                # Disable ticks.
                ax.xaxis.set_ticks_position('bottom')
                ax.yaxis.set_ticks_position('left')
    
    hide_spines()
    show()
    

    只需在show() 之前调用hide_spines(),它就会将它们隐藏在show() 显示的所有数字中。除了花时间修补matplotlib 并添加rc 对所需选项的支持之外,我想不出更简单的方法来更改大量数字。

    【讨论】:

      【解决方案2】:

      要让matplotlib不绘制上下棘刺,可以在matplotlibrc文件中设置如下

      axes.spines.right : False
      axes.spines.top : False
      

      【讨论】:

      • 你还能从 matplotlibrc 文件中删除顶部和右侧轴的刻度吗?
      • @jkokorian:在即将发布的matplotlib 2.0.0 版本中,您可以设置xtick.topytick.right 选项。
      【解决方案3】:
      ax.spines["top"].set_visible(False)    
      ax.spines["right"].set_visible(False)    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-12
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        相关资源
        最近更新 更多