I am trying to plot a few variables with x-axis datetime ranging over several years. I want my final result to have the x-axis range from Jan to Dec and showing different colored lines for each year and value.
Similar to this:
I convert my “Date” column to datetime, and can also extract the year portion.
df[‘Date’]=pd.to_datetime(df[‘Date’],errors=‘coerce’)
df[‘year’]=df[‘Date’].dt.year
df[‘mthday’]=df[‘Date’].dt.strftime(‘%d-%b’)
df=df.sort_values(by=‘Date’)
plot=px.line(df,x=‘Date’,y=‘Systolic ‘,color=‘year’)
plot.update_layout(xaxis_tickformat=’%d-%b’)
With this, the different years are correctly shown in different colors, and the x-axis labels are correctly showing day and month, but the x-axis spans several years. I want it to only show Jan to Dec. (i.e: collapse the graphs in the picture below w the x-axis showing only one set of twelve months)
I have also tried to change the x to df[‘mthday’] but then the graphs become jumbled up. (I think it’s because the strftime for mthday makes the value in that column not a datetime???)
How do I plot with different years and x-axis only showing Jan to Dec?