出于一个奇怪的原因,我找不到在 Python 的 matplotlibrc 文件中指定 spines 配置的方法。关于如何使 matplotlib 默认不绘制上脊和右脊有什么想法吗?
(来源:sourceforge.net)
更多关于 matplotlib 中脊柱的信息是 here
谢谢
最佳答案
为了隐藏子图的右侧和顶部书脊,您需要将相关书脊的颜色设置为'none'
,并将刻度位置设置为 'left'
用于 xtick,'bottom'
用于 ytick(为了隐藏刻度线和书脊)。
不幸的是,目前这些都不能通过 matplotlibrc
访问。 matplotlibrc
中指定的参数经过验证,然后存储在名为 rcParams
的字典中。然后由各个模块检查此字典中的键,其值将作为它们的默认值。如果他们不检查其中一个选项,则该选项不能通过 rc
文件更改。
由于 rc
系统的性质以及书脊的编写方式,更改代码以允许这样做并不简单:
Spines 当前通过用于定义轴颜色的相同 rc
参数获得它们的颜色;你不能将它设置为 'none'
而不隐藏你所有的轴图。它们也不知道它们是 top
、right
、left
还是 bottom
— 实际上只有四个单独的书脊存储在字典中。单独的 spine 对象不知道它们构成了图的哪一侧,因此您不能只添加新的 rc
参数并在 spine 初始化期间分配适当的参数。
self.set_edgecolor( rcParams['axes.edgecolor'] )
(./matplotlib/lib/matplotlib/spines.py,__init__(),第 54 行)
如果您有大量现有代码,手动向每个轴参数添加轴参数会过于繁琐,您可以交替使用辅助函数来遍历所有轴对象并为您设置值。
这是一个例子:
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
对所需选项的支持之外,我想不出更简单的方法来更改大量图形。
关于python - 在 matplotlibrc 中设置 spine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3439344/