简体   繁体   English

将 matplotlib x 轴更改为仅包括年份

[英]Change matplotlib x-axis to include years only

I have the following panda dataframe:我有以下熊猫dataframe:

在此处输入图像描述

When plotting a line graph using Matplotlib, the x-axis (dates) are all squashed together.使用 Matplotlib 绘制折线图时,x 轴(日期)都被挤压在一起。 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非常感谢

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.这将用年份替换 x 轴,代替ticks_data ,您可以添加使用您选择的列表,您可以从 pandas DataFrame 本身派生。

Use groupby to only display mean popularity for each year,使用groupby仅显示每年的平均流行度,
then use reset_index() to convert a grouped object into a new dataframe.然后使用reset_index()将分组的 object 转换为新的 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")

Convert Mes to datetime format, it will take care of chronology(across visualization packages) and assign appropriate x-ticks and intervals.将 Mes 转换为日期时间格式,它将处理年表(跨可视化包)并分配适当的 x-ticks 和间隔。 It does not answer your question specifically but I presume your need is to declutter your plot.它没有具体回答您的问题,但我认为您需要整理您的 plot。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM