python - 这个底部边距从哪里来?

标签 python pandas matplotlib plot

我正在将大量小折线图塞到一个图中。有时,根据我的数据,我会留下相对较大的底部边距。这并非特定于子图,但也可能仅发生在一个轴上。一个例子:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.Series([1, 2, 2, 4, 5], index=pd.date_range('2023', periods=5))
df = df.drop_duplicates()        # Without gaps as is well

fig = plt.figure()
plt.subplots_adjust(0, 0, 1, 1)  # No margins
# ... Lots of stuff/subplots might happen here...

df.plot(xticks=[])               # Depending on df, leaves a bottom margin
plt.show()

这会在底部留下很大的边距:

result with margin

这是为什么呢?有解决办法吗?

最佳答案

经过一番挖掘,我自己找到了原因。事实证明,pandas 将日期 x 轴特殊对待(format_date_labels)。除非日期范围完全规则(没有间隙),否则会显式设置 bottom=0.2(通过 fig.subplots_adjust)。至少当日期间隙位于底部子图之一时。

这带来了一个简单的解决方法:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.Series([1, 2, 2, 4, 5], index=pd.date_range('2023', periods=5))
df = df.drop_duplicates()        # Without gaps as is well

fig = plt.figure()
plt.subplots_adjust(0, 0, 1, 1)  # No margins
# ... Lots of stuff/subplots might happen here...

df.plot(xticks=[])               # Depending on df, leaves a bottom margin
plt.subplots_adjust(bottom=0)    # Fix!
plt.show()

现在结果没有预期的余量:

enter image description here

我不确定这种行为是否是 pandas 的错误。我认为记录解决方法是个好主意。至少对我来说,因为我将来可能会在这里找到它。

关于python - 这个底部边距从哪里来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75329174/

相关文章:

python - Pandas 如何将数组放在单个数据框单元格中?

python - 如何在不耗尽内存的情况下读取 tsv 文件并将它们存储为 hdf5?

python - 如何将图像存储在变量中

Python绘制极坐标方程

python - 使用条件 python 查找最小值

python - MT19937RNG如何生成小于32位的随机数?

python - 使用 pandas 导出 DataFrame 时使用 ExcelWriter 有哪些优点?

Python matplotlib 圆环图在一个楔形上具有较小的宽度

Python/Django : Cannot import GeoIP

python - 类型错误 : object cannot be converted to an IntegerDtype