【问题标题】:Adjusting size of matplot lib figure (including title and tick labels)- hidden when sizing down figure调整 matplotlib 图形的大小(包括标题和刻度标签)- 缩小图形时隐藏
【发布时间】:2021-04-30 23:58:41
【问题描述】:

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

我已经使用 spyder 在 python 3.8 中完成了所有工作,但是当我将它加载到我的服务器(使用 python 3.4)时,它会创建一个巨大的绘图,我必须在浏览器上滚动。当我将 figsize 更改为小于 10 的高度时,它会切断 x 轴标签和刻度标签。我已将 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)

【问题讨论】:

  • 我猜你的一个显示器显示的东西是另一个显示器每英寸点数的两倍。

标签: python pandas matplotlib base64


【解决方案1】:

我认为对您来说最简单的方法是添加 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

【讨论】:

  • 我在您建议的我的代码位置添加了: plt.tight_layout(pad=14, h_pad=None, w_pad=None, rect=None) 并且它有效。谢谢!!
猜你喜欢
  • 2013-07-23
  • 2015-08-12
  • 2012-02-05
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多