Reputation: 3
I'm creating an html page with a dropdown menu. When the user hits the "submit" button after making their selection from the dropdown menu, the cgi script runs and pulls data from a csv file, plots it using matplotlib, and then displays the plot using base64. The plot has dates along the x-axis and percentage on the y-axis.
I've got it all working in python 3.8 using spyder, but when I load it to my server (which uses python 3.4) it creates a huge plot that I have to scroll on the browser. When I change the figsize to height less than 10, it cuts off the x-axis label and tick labels. I've rotated the xticks 30* to make them readable. How do I essentially "zoom out" on the entire figure including tick & axis labels?
Here's the portion of my code that creates the plot:
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)
Upvotes: 0
Views: 461
Reputation: 939
I think that the simplest way for you is to add
plt.tight_layout
before plt.savefig
like this:
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)
more info about it : https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html
Upvotes: 1