如何强制在matplotlib上设置x刻度,或设置没有年份的日期时间类型 [英] How to force set x ticks on matplotlib, or set datetime type with no year
问题描述
因此,我有一个函数将获取一个pandas数据框并对其进行绘制,并显示一些错误度量,并且我也有一个函数将获取一个带有日期时间类型索引的pandas数据框,并获取每日平均值数据框中的值.问题是,当我尝试绘制每日平均值时,使用matplotlib看起来确实很糟糕,因为它将每日绘制为x轴上的单独刻度.我将所有这些代码保存在名为Hydrostats的程序包中,每日平均功能的github存储库源代码为此处,绘图功能的源代码为
So I have a function that will take a pandas dataframe and plot it, along with displaying some error metrics, and I also have a function that will take a pandas dataframe with a datetime type index, and take the daily average of the values in the dataframe. The problem is, when I try to plot the daily average, it looks really bad with matplotlib because it plots everyday as a seperate tick on the x axis. I have all this code in a package called Hydrostats, the github reposity source code for the daily average function is here, and the source code for the plotting function is here. The plot for a linear time series is is below. The Daily Average plot is shown below
如您所见,您看不到任何x轴刻度,因为它们都被挤压在一起了.
As you can see, you can't see any of the x axis ticks because they are all so squished together.
推荐答案
您可以通过 ax.set_xticklabels()
.
You can set the ticks used for the x axis via ax.set_xticks()
and labels via ax.set_xticklabels()
.
例如,您可以为该方法提供要使用的日期列表,例如当前pd.DataFrame
索引(df.index[::20]
)的每20个值,然后按如下所示设置日期字符串的格式.
For instance you could just provide that method with a list of dates to use, such as every 20th value of the current pd.DataFrame
index (df.index[::20]
) and then set the formatting of the date string as below.
# Get the current axis
ax = plt.gca()
# Only label every 20th value
ticks_to_use = df.index[::20]
# Set format of labels (note year not excluded as requested)
labels = [ i.strftime("%-H:%M") for i in ticks_to_use ]
# Now set the ticks and labels
ax.set_xticks(ticks_to_use)
ax.set_xticklabels(labels)
注释
如果标签仍然重叠,您还可以通过传递旋转参数(例如ax.set_xticklabels(labels, rotation=45)
)来旋转标签.
If labels still overlap, you could also rotate the them by passing the rotatation argument (e.g. ax.set_xticklabels(labels, rotation=45)
).
此处提供了有关时间字符串格式的有用参考: http://strftime.org .
There is a useful reference for time string formats here: http://strftime.org.
这篇关于如何强制在matplotlib上设置x刻度,或设置没有年份的日期时间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!