Reputation: 31
I have the following panda dataframe:
When plotting a line graph using Matplotlib, the x-axis (dates) are all squashed together. As seen below:
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
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
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
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