我已经定制了2D绘图,我想在将来的绘图中重复使用轴,标签,字体大小等设置。例如,我为此特定情节设置了以下设置,并且我希望能够以某种方式将它们保存为"样式"用于未来的数字:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2, 2)
y = x**2
fig, ax = plt.subplots()
# text specific to this plot, but attributes common to all
ax.plot(x, y, label='$y = x^2$', linewidth=2)
ax.set_xlabel('$x$', fontsize=20)
ax.set_ylabel('$y$', fontsize=20)
ax.set_title('Graph of $y = x^2$', fontsize=20)
# common to all plots
ax.legend(loc='best')
ax.spines['bottom'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.xaxis.label.set_color('grey')
ax.yaxis.label.set_color('grey')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(colors='grey')
plt.show()
特别是,对于# text specific...
下的前四行,函数中的字符串特定于此图,但像linewidth=2
这样的属性我希望将来分享。 # common to all plots
下的行是我想要分享的所有未来数据的属性。有没有办法可以将其保存为"样式"为了便于使用,可能作为plt.figure()
的一些论据?
答案 0 :(得分:1)
Matplotlib允许在许多绘图设置的预定义参数意义上使用样式。
您会在matplotlib customization article中找到一个很好的介绍和示例案例。
一种选择是创建自己的样式文件。
可以通过print matplotlib.get_configdir()
找到matplotlib查找样式文件的目录。在此文件夹中,创建一个名为stylelib
的子文件夹(如果它尚不存在)。
然后,您将在其中创建一个名为mystyle.mplstyle
的文件。
您的案例中此文件的内容为
### MATPLOTLIBRC FORMAT
lines.linewidth : 2 # line width in points
axes.edgecolor : grey # axes edge color
axes.titlesize : 20 # fontsize of the axes title
axes.labelsize : 20 # fontsize of the x any y labels
axes.labelcolor : grey
axes.spines.left : True # display axis spines
axes.spines.bottom : True
axes.spines.top : False
axes.spines.right : False
xtick.top : False # draw ticks on the top side
xtick.bottom : True # draw ticks on the bottom side
xtick.color : grey # color of the tick labels
ytick.left : True # draw ticks on the left side
ytick.right : False # draw ticks on the right side
ytick.color : grey # color of the tick labels
legend.loc : best
在您通过print plt.style.available
获取的列表中,您现在应该找到一个条目mystyle
。
然后,您的python脚本可以通过plt.style.use('mystyle')
读取此样式。
您的绘图脚本可以缩减为
import matplotlib.pyplot as plt
plt.style.use('mystyle')
fig, ax = plt.subplots()
x=range(8)
y=[1,5,4,3,2,7,4,5]
ax.plot(x, y, label='$y = x^2$')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_title('Graph of $y = x^2$')
ax.legend()
plt.show()
请注意,您仍然需要致电ax.legend()
以获取图例。
如果某些内容无法按预期运行,请询问有关它的具体且更狭隘的问题。