[Chartjs]-How to create a line chart indicating which month a user wrote more or less blogs?

1👍

Since you are working on Django, I would draw this graph with plotly.

In your views.py:

import plotly.offline as pyo
import plotly.graph_objs as go
import datetime as dt
import calendar



time_values = Blog.objects.all().order_by("created_at")

time_values = [ element.created_at for element in time_values ]

time_values = [ element.month for element in time_values ]



published_amounts = [ 1 for element in time_values ]

new_time_values = [ time_values[0] ]
published_amounts = [ 0 ]

j=0

# the cycle prevents mixing months from different years
for i in range( 1, len(time_values) ):

    if time_values[i]==time_values[i-1]:
        published_amounts[j] = published_amounts[j] + 1

        
    else:   
        new_time_values.append(time_values[i])
        published_amounts.append(1)        
        j=j+1


new_time_values = [calendar.month_name[element] for element in new_time_values ]      
        

post_line = go.Scatter(
                    x=new_time_values, 
                    y=published_amounts,
                    mode='lines+markers',
                    name="Published posts",              
                    )

data = [ post_line, ]  

layout = go.Layout(showlegend=True, )

fig = go.Figure(data=data, layout=layout)

plt_div = pyo.plot(fig, output_type='div')

context_dict={
        "plt_div":plt_div
                }

return render(request, 'your_page.html', context_dict)

Then in your template you simply have to put

{{plt_div}}

where you want your graph to be displayed.

Leave a comment