python - 如何确保matplotlib图x轴上标签之间的间距均匀?

标签 python matplotlib

我收到了一份数据,我需要为其找到直方图。因此,我使用 pandas hist() 函数并使用 matplotlib 绘制它。该代码在远程服务器上运行,因此我无法直接看到它,因此我保存了图像。这是图像的样子

enter image description here

下面是我的代码

import matplotlib.pyplot as plt

df_hist = pd.DataFrame(np.array(raw_data)).hist(bins=5) // raw_data is the data supplied to me
plt.savefig('/path/to/file.png')
plt.close()

正如您所看到的,x 轴标签是重叠的。所以我像这样使用了这个函数plt.tight_layout()

import matplotlib.pyplot as plt

df_hist = pd.DataFrame(np.array(raw_data)).hist(bins=5)
plt.tight_layout()
plt.savefig('/path/to/file.png')
plt.close()

现在有一些改进

enter image description here

但标签仍然太接近。有没有办法确保标签不会相互接触并且它们之间有公平的间距?我还想调整图像大小以使其变小。

我在这里检查了文档https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html但不确定 savefig 使用哪个参数。

最佳答案

由于 raw_data 还不是 pandas 数据帧,因此无需将其转换为数据帧来进行绘图。相反,您可以直接使用 matplotlib 进行绘图。

有很多不同的方法可以实现您想要的目标。我将首先设置一些与您的数据类似的数据:

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gamma

raw_data = gamma.rvs(a=1, scale=1e6, size=100)

如果我们继续使用 matplotlib 创建直方图,我们可能会发现 xticks 靠得太近:

fig, ax = plt.subplots(1, 1, figsize=[5, 3])
ax.hist(raw_data, bins=5)
fig.tight_layout()

enter image description here

无论间距如何,所有零的 xticks 都很难阅读。因此,您可能希望做的一件事是使用科学格式。这使得 x 轴更容易解释:

ax.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

enter image description here

不使用科学格式的另一种选择是旋转刻度(如评论中所述):

ax.tick_params(axis='x', rotation=45)
fig.tight_layout()

enter image description here

最后,您还提到了更改图像的大小。请注意,最好在初始化图窗时完成此操作。您可以使用 figsize 参数设置图窗的大小。以下将创建一个宽 5 英寸、高 3 英寸的图形:

fig, ax = plt.subplots(1, 1, figsize=[5, 3])

关于python - 如何确保matplotlib图x轴上标签之间的间距均匀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54999593/

相关文章:

python - 如何使用python向服务器提交表单并通过互联网从服务器获取csv文件?

python - matplotlib无法绘制彩色希尔伯特曲线?

python - 如何直接以 gzip 格式保存 pandas 数据框?

Python plot - 堆叠图像切片

python - 将 pandas 数据框的 3 列绘制为热图

python - Django 从 PostgreSQL 特定的 ArrayField 中获取最小值和最大值,其中包含 IntegerField(s)

python - GAE Python2.7客户端证书认证

python - Matplotlib Graphs下的渐变填充

python - 将两个用户定义函数中的 ax 和 fig 合并到一个图中?

Python plot() 函数