调整 matplotlib 图的大小(包括标题和刻度标签)- 缩小图时隐藏

Adjusting size of matplot lib figure (including title and tick labels)- hidden when sizing down figure

我正在创建一个带有下拉菜单的 html 页面。当用户从下拉菜单中做出选择后点击“提交”按钮时,cgi 脚本运行并从 csv 文件中提取数据,使用 matplotlib 绘制它,然后使用 base64 显示该图。该图在 x-axis 上有日期,在 y-axis 上有百分比。

我使用 spyder 在 python 3.8 中完成了所有工作,但是当我将它加载到我的服务器(使用 python 3.4)时,它创建了一个巨大的图,我必须滚动在浏览器上。当我将 figsize 更改为小于 10 的高度时,它会切断 x-axis 标签和刻度标签。我将 xticks 旋转了 30* 以使其可读。我如何从根本上“缩小”整个图形,包括刻度和轴标签?

这是我创建情节的代码部分:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import base64

    fig, ax = plt.subplots(figsize=(15, 10))  
    df = pd.read_csv(filepath, header=1, parse_dates=['Report_Date'], index_col=['Report_Date'])  
    ax.plot(df.index.values, df['colname'], color='teal')  
    ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=None, symbol='%', is_latex=False))   
    plt.xlabel('Report Date')
    plt.ylabel('ylabel')
    plt.title('title') 
    plt.xticks(rotation=30, ha='right')   
    plt.savefig('picture.png', dpi=200)  
    data_uri = base64.b64encode(open('picture.png','rb').read()).decode('utf-8')  
    img_tag = '<img src='data:image/png;base64,{0}>'.format(data_uri)  
    print(img_tag)

我认为最简单的方法是添加 plt.tight_layoutplt.savefig

之前

像这样:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import base64

fig, ax = plt.subplots(figsize=(15, 10))  
df = pd.read_csv(filepath, header=1, parse_dates=['Report_Date'], index_col=['Report_Date'])  
ax.plot(df.index.values, df['colname'], color='teal')  
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=None, symbol='%', is_latex=False))   
plt.xlabel('Report Date')
plt.ylabel('ylabel')
plt.title('title') 
plt.xticks(rotation=30, ha='right')
plt.tight_layout()
plt.savefig('picture.png', dpi=200)  
data_uri = base64.b64encode(open('picture.png','rb').read()).decode('utf-8')  
img_tag = '<img src='data:image/png;base64,{0}>'.format(data_uri)  
print(img_tag)

更多信息:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html