Home > Software design >  How to show only the monthly ticks in the x axis when using DataFrame.plot()
How to show only the monthly ticks in the x axis when using DataFrame.plot()

Time:02-26

I am plotting daily data directly using the pandas DataFrame plotting method as shown below.

gna_plot[['Forecast', 'Off', 'Ans']].plot(xticks=gna_plot.index, figsize=(16, 8), subplots=True)

If I use this method then I get something like this in the plot which is obviously very messy. I only want to show the first or last date of every month. How can I show just those 12 xticks in this plot?

enter image description here

CodePudding user response:

You can use this:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates


 ax = plt.gca()
 # start by your date and then your data
 ax.plot(region['Date'],region["temperature(°C)"]) # daily data
 # You can change the step of range() as you prefer (now, it selects each third month) 
 ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=range(1,12,3)))
 # you can change the format of the label (now it is 2016-Jan)  
 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
    
 plt.setp(ax.get_xticklabels(), rotation=90) 
 plt.show()

You can read more enter image description here

CodePudding user response:

The crucial step is to convert the x axis data to datetime.

Here is an example using COVID data from ourworldindata.org.

import pandas as pd
import matplotlib.pyplot as plt

covidData = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv')

covidData.date = pd.to_datetime(covidData.date)  # This is the datetime conversion.

covidDataDenmark = covidData[covidData.location=='Denmark']  # Selecting one country.

covidDataDenmark.plot(x='date', y='new_cases_smoothed_per_million')

Pandas plot

Alternatively, Matplotlib is a good choice. In this case, rotate the xticks by 45 degrees for better readability.

plt.plot(covidDataDenmark.date, covidDataDenmark.new_cases_smoothed_per_million)
plt.xticks(rotation=45)
plt.show()

Matplotlib plot

  • Related