【问题标题】:Where does this bottom margin come from?这个底边距从何而来?
【发布时间】:2023-02-03 05:36:50
【问题描述】:
我将许多小折线图塞进了一个图形中。有时我会留下相对较大的底边距,具体取决于我的数据。这不是特定于子图,但也可能只发生在一个轴上。一个例子:
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()
这在底部留下了很大的余量:
为什么是这样?有解决方法吗?
【问题讨论】:
标签:
python
pandas
matplotlib
plot
【解决方案1】:
经过一番挖掘,我自己找到了原因。事实证明,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()
现在结果没有预期的余量:
我不确定这种行为是否是熊猫的错误。我认为记录解决方法是个好主意。至少对我来说,因为我将来可能会在这里找到它。