I am trying to render the plot generated by seaborn on Django template.
I have the following code in my views.py:
def booking_hour_plot():
qs = bookings_today()
df = read_frame(qs)
plot = sns.countplot(data=df)
return plot
def render_stats_page(request):
#general info
user_count = total_users_until_now()
cancel_rate = activity_cancel_rate()
#activity/booking details
activity_set = activities_today()
booking_set = bookings_today()
plot = booking_hour_plot()
return render(request, "stats.html", {'name':'Avonmore Statistics',
'total_user':int(user_count),
'cancel_rate': round(float(cancel_rate), 2),
'booking_count_today': booking_set.count(),
'activity_count_today': activity_set.count(),
'activities_today': activity_set,
'bookings_today': booking_set,
'booking_hour_plot': plot,
})
And I have a html template called stats.html that containing the plot. The templates directory and views.py are in the same directory:
<li>Real Time Plot: {{booking_hour_plot}}</li>
However, the rendered html page is not really showing the plot. It's more like the plot object: enter image description here
Any Idea how to put the real plot on the html page, rather than this plot object?
Try saving and encoding your plot as png file, then display as <img> element tag by this way:
from io import BytesIO
import base64
def booking_hour_plot():
qs = bookings_today()
df = read_frame(qs)
plot = sns.countplot(data=df)
plot_file = BytesIO()
plot.savefig(plot_file, format='png')
encoded_file - base64.b64encode(plot_file.getValue())
return encoded_file
in stats.html:
<li>Real Time Plot: <img src='data:image/png;base64,{{booking_hour_plot}}'/></li>