简体   繁体   English

使用matplotlib绘制df时如何在图表上获取x轴标签

[英]How to get x axis labels on chart when plotting df using matplotlib

I have minutely data in a dataframe.我在数据框中有详细的数据。 I'm trying to plot on y axis column C , against the index column date.我正在尝试针对索引列日期在 y 轴列C上绘图。 How can I show 5 dates as x-axis labels?如何将 5 个dates显示为 x 轴标签?

Currently, I try to plot like this:目前,我尝试这样绘制:

df['C'].plot(figsize=(16,6))

However, I can't see any x-axis labels.但是,我看不到任何 x 轴标签。

df=pd.DataFrame([["2020-07-01 00:00:00",2],["2020-07-01 00:01:00",3]],columns=['date','C'])

Here is the solution :这是解决方案:

  • Read the dataframe :读取dataframe
df=pd.DataFrame([["2020-07-01 00:00:00",2],["2020-07-01 00:01:00",3]],columns=['date','C'])
  • Change the dtype of date to pandas datetime64[ns] .datedtype更改为 pandas datetime64[ns]
df.date = pd.to_datetime(df.date)
  • Plot with supplying date as x :绘制提供datex
df.plot(x='date')

Output :输出 :

在此处输入图片说明

You can change the frequency of the ticks using mdates.DateFormatter as explained in the answer here :您可以更改使用刻度线的频率mdates.DateFormatter作为答案解释在这里

## borrowed from https://stackoverflow.com/questions/14946371/editing-the-date-formatting-of-x-axis-tick-labels-in-matplotlib
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d') ## change '%d' depending on your requirement
ax.xaxis.set_major_formatter(myFmt)

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

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