Matplotlib绘图中底部空白的成因及解决办法
问题成因与解决办法
成因分析
当用pandas的df.plot()绘制带日期类型索引的数据时,哪怕设置了xticks=[]隐藏刻度,matplotlib的日期轴布局逻辑仍会默认给刻度标签预留显示空间。再加上pandas绘图函数内部会触发自动布局调整,直接覆盖了你设置的plt.subplots_adjust(0, 0, 1, 1),最终导致底部出现多余空白。
解决办法
1. 强制指定坐标轴位置
获取当前绘图轴,手动设置它占满整个figure,绕过自动布局的影响:
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() fig = plt.figure() ax = plt.gca() # 获取当前坐标轴对象 df.plot(xticks=[], ax=ax) ax.set_position([0, 0, 1, 1]) # 左、底、宽、高均设为0或1,占满整个figure plt.show()
2. 改用matplotlib原生绘图
直接调用matplotlib的plot()方法,避免pandas绘图函数的自动布局干扰:
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() fig = plt.figure() plt.subplots_adjust(0, 0, 1, 1) plt.plot(df.index, df.values) plt.xticks([]) # 隐藏x轴刻度 plt.show()
3. 彻底隐藏x轴标签并调整边距
明确关闭x轴标签,再手动设置底部边距为0,确保覆盖自动布局:
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() fig = plt.figure() ax = df.plot(xticks=[]) ax.tick_params(axis='x', labelbottom=False) # 彻底隐藏x轴标签 plt.subplots_adjust(bottom=0) # 设置底部边距为0 plt.show()
内容的提问来源于stack exchange,提问作者Michel de Ruiter
相关产品推荐
相关产品推荐

