2021年4月29日星期四

Why are date not displaying correctly on html when using matplotlib/pandas/base64 to create png using python/cgi?

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) to use in html it cuts off the dates and displays only the year, not the month and day. The data in the csv also includes time and "am/pm" neither of which should display. How do I get the year, month, and day to display for the date in html? I'm not sure if it's an issue with how I've formatting the png or an issue with the date display.

Here's the portion of my code that creates the plot:

    fig, ax = plt.subplots(figsize=(5, 3.5))        df = pd.read_csv(filepath, header=1, parse_dates=['Report_Date'], index_col=['Report_Date'])        ax.plot(df.index.values, df['PctVaccinatedPopulation'], color='teal')        ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=None, symbol='%', is_latex=False))        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)  

I've tried:

mydateparser = lambda x: pd.datetime.strptime(x, "%m/%d/%Y %H:%M:%S %p")     and then modifying the second line of my code to:    df = pd.read_csv(filepath, header=1, parse_dates=['Report_Date'], date_parser=mydateparser, index_col=['Report_Date'])     

which also works in python 3.8 in spyder but not on the server.

https://stackoverflow.com/questions/67326978/why-are-date-not-displaying-correctly-on-html-when-using-matplotlib-pandas-base6 April 30, 2021 at 09:14AM

没有评论:

发表评论