简体   繁体   English

如何在绘制所有数据集时使用 matplotlib 在 x 轴上仅使用 label 特定日期

[英]How to label only specific dates on the x axis with matplotlib while plotting all the dataset

I want to plot this data frame, with dates on the x-axes and values on the y-axes.我想 plot 这个数据框,日期在 x 轴上,值在 y 轴上。

f_index=pd.date_range(start='1/1/2020', end='1/12/2020')
f_data=np.arange(0,len(f_index))
df=pd.DataFrame(data=f_data, index=f_index,columns=['Example'])

On the x ticks, I want to show only two dates like 2020,3,2 , and 2020,6,8 because are the relevant ones.在 x 刻度上,我只想显示两个日期,例如2020,3,22020,6,8 ,因为它们是相关的。

So I was thinking about something like that:所以我在想这样的事情:

x1=(pd.Timestamp(2020,3,2)-f_index[0]).days
x2=(pd.Timestamp(2020,6,8)-f_index[0]).days
xx=[x1,x2]
fig2, ax2= plt.subplots(figsize=(6,4),
                          facecolor='white', dpi=300)
ax2.plot(df.index,df.Example)
#ax2.set_xticks(xx)
#ax2.set_xlabel(xx)
plt.show()

but it doesn't work.但它不起作用。

I tried different methods and read different questions, but I did not find one with my specific answer.我尝试了不同的方法并阅读了不同的问题,但我没有找到我的具体答案。

This is what can I get at the moment for simplicity I rotated the dates with ax2.tick_params(axis='x',rotation=90) but is not in the code above.为简单起见,这是我目前可以得到的,我用ax2.tick_params(axis='x',rotation=90)旋转了日期,但不在上面的代码中。

在此处输入图像描述

This is what I would like to get这就是我想要得到的

在此处输入图像描述

For me is important to understand how dates work because then I want to plot two straight lines in correspondence of the specific dates, something like this.对我来说,了解日期的工作原理很重要,因为我想 plot 两条直线对应于特定的日期,就像这样。

在此处输入图像描述

Your code looks fine:您的代码看起来不错:

from matplotlib import pyplot as plt
import datetime

# create dummy data
dates = []
data = []
for i in range(1,24):
    dates.append( datetime.date(2020,12,i) )
    data.append( i )
# open figure + axis
fig, ax = plt.subplots()
# plot data
ax.plot( dates, data)
# rotate x-tick-labels by 90°
ax.tick_params(axis='x',rotation=90)

create this output创建这个 output 自动xticks while adding在添加的同时

ax.set_xticks( [dates[5],dates[6],dates[16]] )

leads to this graph导致这张图在此处输入图像描述

If you would like to have a grid, you can simply switch it on via the ax.grid() method (you can also say, on which axis; axis='both is default):如果你想要一个网格,你可以简单地通过ax.grid()方法打开它(你也可以说,在哪个轴上; axis='both是默认值):

ax.grid(True)

大梁

Now, if you want to have minor ticks in between (let's say, you want to display every tick-date), it gets a bit trickier because you need to set a multiplicator of the ticks... in our case the non-equidistant spacing makes this a little non-intuitive, but let's see:现在,如果你想在两者之间有小刻度(比如说,你想显示每个刻度日期),它会变得有点棘手,因为你需要设置刻度的乘数......在我们的例子中是非等距的间距使这有点不直观,但让我们看看:

from matplotlib.ticker import AutoMinorLocator
minor_locator = AutoMinorLocator(1)
ax.xaxis.set_minor_locator(minor_locator)
ax.grid(which='minor',linestyle=':')

在此处输入图像描述

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

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