gpt4 book ai didi

python - 我如何 'correct' 这个 matplotlib 绘图例程?

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:39 25 4
gpt4 key购买 nike

我对 matplotlib 提供的编码范例感到困惑。我正在使用如下代码绘制一些数据:

fig=plt.figure(figsize=fig_size)  # plt=pyplot defined above
axes1 = fig.add_subplot(111)
axes1.plot(temp, depth, 'k-')
axes1.set_ylim(-600,0)
axes1.set_ylabel(r'Depth $(m)$')
axes1.set_xlim(0,80)
axes1.set_xlabel(r'Temperature (\textcelsius)')
axes1.set_xticks(np.arange(0,100,20))
axes1.grid(True)
plt.savefig(savedir + 'plot.svg', transparent=True)

我宁愿使用 mpl 的面向对象风格,也不愿使用 pylab 的便利函数。所以问题是,如果我只想非交互地绘制一条曲线,我是否使用了正确的图形创建风格? (第 1 和第 2 行)。似乎需要很多单独的调用来格式化轴标签等。

最佳答案

你所做的看起来不错。 (我同意,仅使用 pyplot 来创建图形并使用 OO API 来处理其他所有内容会更简洁。)

如果您希望在一次调用中制作图形和坐标轴,请使用 plt.subplots .

此外,我发现使用 fig.savefig 而不是 plt.savefig 更简洁。在这种情况下这无关紧要,但这样您就不必担心状态机界面中哪个图形处于“事件”状态。

最后一件事,您可以通过一次调用 axes1.axis(...) 来设置 x 和 y 限制。这纯粹是偏好问题。 set_xlimset_ylim 可以说是一种更具可读性的方式。

“setter”和“getter”很烦人,但如果我没记错的话,可以追溯到 python 没有属性的时候。它们被保留为主要方法,部分是为了向后兼容,部分是为了像 plt.setp 这样的“matlab 主义”。更容易写。事实上,如果你愿意,你可以做到

plt.setp(ax, xlabel='Xlabel', ylabel='Ylabel', xticks=range(0, 100, 20))

这避免了必须执行三个单独的调用来设置 xlabel、ylabel 和 xticks。但是,我个人倾向于避免它。我发现在大多数情况下最好稍微详细一些。不过,如果您觉得它更简洁或更方便,那么使用 setp 也没有错。

作为我如何编写它的示例:

import matplotlib.pyplot as plt
import numpy as np

depth = np.linspace(-600, 0, 30)
temp = (4 * np.random.random(depth.size)).cumsum()

fig, ax = plt.subplots()
ax.plot(temp, depth, 'k-')
ax.axis([0, 80, -600, 0])
ax.set_ylabel(r'Depth $(m)$')
ax.set_xlabel(r'Temperature $(^{\circ}C)$')
ax.set_xticks(np.arange(0, 100, 20))
ax.grid(True)

fig.savefig('plot.svg', transparent=True)
plt.show()

enter image description here

关于python - 我如何 'correct' 这个 matplotlib 绘图例程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10070793/

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