我正在将大量小折线图塞到一个图中。有时,根据我的数据,我会留下相对较大的底部边距。这并非特定于子图,但也可能仅发生在一个轴上。一个例子:
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()
这会在底部留下很大的边距:
这是为什么呢?有解决办法吗?
最佳答案
经过一番挖掘,我自己找到了原因。事实证明,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()
现在结果没有预期的余量:
我不确定这种行为是否是 pandas 的错误。我认为记录解决方法是个好主意。至少对我来说,因为我将来可能会在这里找到它。
关于python - 这个底部边距从哪里来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75329174/