gpt4 book ai didi

python - 在未来绘图中使用自定义图形设置

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:49 25 4
gpt4 key购买 nike

我已经自定义了一个 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 之类的属性我想分享 future 的情节。 # common to allplots 下的线条是我希望所有 future 的数据共享的属性。有没有办法可以将其保存为“样式”以便于使用,也许作为 plt.figure() 的一些参数?

最佳答案

Matplotlib 允许在许多绘图设置的预定义参数意义上使用样式。

您可以在matplotlib customization article中找到很好的介绍和示例案例。 。

一种选择是创建您自己的样式文件。matplotlib 查找样式文件的目录可以通过 print matplotlib.get_configdir() 找到。在此文件夹中创建一个名为 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() 来获取图例。

如果某些内容未按预期工作,请提出一个具体且更具体的问题。

关于python - 在未来绘图中使用自定义图形设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com