Sean
Sean

Reputation: 31

Change matplotlib x-axis to include years only

I have the following panda dataframe:

enter image description here

When plotting a line graph using Matplotlib, the x-axis (dates) are all squashed together. As seen below:

enter image description here

Do you know how this can be done? I am relatively new to this and the code I have used is the following:

import matplotlib.pyplot as plt
plt.plot(df_temp['Mes'], df_temp['data science'], label='data science')
plt.plot(df_temp['Mes'], df_temp['machine learning'], label='machine learning')
plt.plot(df_temp['Mes'], df_temp['deep learning'], label='deep learning')
plt.xlabel('Date')
plt.ylabel('Popularity')
plt.title('Popularity of AI terms by date')
plt.grid(True)
plt.legend()

Thanks alot

Upvotes: 0

Views: 3160

Answers (3)

Abhijith
Abhijith

Reputation: 58

Convert Mes to datetime format, it will take care of chronology(across visualization packages) and assign appropriate x-ticks and intervals. It does not answer your question specifically but I presume your need is to declutter your plot.

df_temp.Mes=pd.to_datetime(df_temp.Mes)

Upvotes: 0

Newcomer
Newcomer

Reputation: 73

Use groupby to only display mean popularity for each year,
then use reset_index() to convert a grouped object into a new dataframe.

new_dataframe = pd.DataFrame({'popularity': df.groupby(df['Mes'].dt.year)['a'].mean()}).reset_index()
plt.plot(new_dataframe['Mes'], new_dataframe['popularity'], label='data science')
plt.xlabel("Year")
plt.ylabel("Popularity")

Upvotes: 0

Subhrangshu Adhikary
Subhrangshu Adhikary

Reputation: 404

ticks_data = [2004,2005,2006]
plt.xticks(ticks_data)

Or you can also try,

plt.xticklabels(ticks_data, fontsize=14)

This will replace the x axis with years, in place of ticks_data , you can add use a list of your choice which you may derive from the pandas DataFrame itself.

Upvotes: 1

Related Questions