如何修改X轴下面混乱和重叠的日期标签

7

df(Pandas DataFrame)有两列:Date(作为datetime64)和Amount(作为float)。

我使用条形图将Amount列的值绘制在时间轴上:

sns.barplot(x="Date", y="Amount", data=df)
plt.show()

然而,日期标签非常混乱(见图片)。在Pandas中处理它的一种优雅方式是什么?我正在考虑从标签中删除月份和年份,或将标签旋转90度。如何执行这些操作,或者是否有更好的选择?谢谢。

Overlapping date labels on x axis


旋转标签后,柱状图显示的日期标签格式为:“2018-09-29T00:00:00.000000000”,尽管print(df [“Date”])以正确的格式显示它们(2018-09-29),我不知道为什么会这样。这是混乱的原因之一,但我认为原始问题仍然存在。 - KMFR
这绝对是一个单独的问题,“如何让pandas将我的日期时间格式化为日期”(很可能已经在这里有答案了 - 朴素地说,您可以只需使用strftime映射到您的df行)。 - 0xdd
当然,这是一个单独的问题,但是通过其他回答的帮助,这并没有完全解决标签混乱的问题。旋转有所帮助,较小的字体更有帮助,最后仅显示日期而不是日期和时间,使标签可读。谢谢。 - KMFR
3个回答

8

这会自动调整SNS图的日期X轴,因此在大多数情况下您不必手动进行调整:

sns_plot.get_figure().autofmt_xdate()

"sns_plot"是您从seaborn绘图函数中创建的本地变量。这个修改改变了日期时间的角度,但如果时间信息也导致重叠,则不会消除它。 完整代码如下: - Mark Andersen
2
被低估的答案 - crypdick
1
这解决了我的问题。谢谢! - Snoopy

4
我会同时进行两项操作:旋转您的x标签并仅使用日期:
import seaborn as sns
import matplotlib.pyplot as plt

# dummy data:
df = pd.DataFrame({'Date':pd.to_datetime(['1999-12-12', '2000-12-12', '2001-12-12']),'Amount':[1,2,3]})

sns.barplot(x="Date", y="Amount", data=df)
# use the original locations of your xticks, and only the date for your label
# rotate the labels 90 degrees using the rotation argument
plt.xticks(plt.xticks()[0], df.Date.dt.date, rotation=90)
plt.tight_layout()
plt.show()

enter image description here


谢谢,这样很好地清理了标签。我不太确定 "plt.xticks()[0]" 是什么意思,我应该把这些日期标签称为 xticks 还是 labels 或其他什么? - KMFR
1
plt.xticks()[0] 是获取当前图表刻度位置的一种方法(还有其他方法)。因此,您可以将原始刻度位置、格式化字符串标签和所需旋转传递给 xticks 属性 - sacuL

2

如果你有大量的日期需要标记,而且希望在更稀疏的时间间隔内进行标记,那么另一个解决方案是:

最初的回答:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# dummy data:
df = pd.DataFrame({'Date':pd.to_datetime(['1999-12-12', '2000-12-12', '2001-12-12',
                                          '2002-12-12', '2003-12-12', '2004-12-12',
                                          '2005-12-12','2006-12-12', '2007-12-12', '2008-12-12']),
                                          'Amount':[1,2,3,4,5,6,7,8,9,10]})

fig, ax = plt.subplots()
sns.barplot(x="Date", y="Amount", data=df, ax=ax)

# set the frequency for labelling the xaxis
freq = int(2)

# set the xlabels as the datetime data for the given labelling frequency,
# also use only the date for the label
ax.set_xticklabels(df.iloc[::freq].Date.dt.date)
# set the xticks at the same frequency as the xlabels
xtix = ax.get_xticks()
ax.set_xticks(xtix[::freq])
# nicer label format for dates
fig.autofmt_xdate()

plt.tight_layout()
plt.show()

点击查看图表

同时,考虑使用seaborn默认的绘图设置,并将日期放在y轴上以便阅读,但这更多是个人偏好。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# set the seaborn asthetics
sns.set()

# dummy data:
df = pd.DataFrame({'Date':pd.to_datetime(['1999-12-12', '2000-12-12', '2001-12-12',
                                          '2002-12-12', '2003-12-12', '2004-12-12',
                                          '2005-12-12','2006-12-12', '2007-12-12', '2008-12-12']),
                                          'Amount':[1,2,3,4,5,6,7,8,9,10]})

fig, ax = plt.subplots()
# plot with a horizontal orientation
sns.barplot(y="Date", x="Amount", data=df, ax=ax, orient='h')

# set the frequency for labelling the yaxis
freq = int(2)

# set the ylabels as the datetime data for the given labelling frequency,
# also use only the date for the label
ax.set_yticklabels(df.iloc[::freq].Date.dt.date)
# set the yticks at the same frequency as the ylabels
ytix = ax.get_yticks()
ax.set_yticks(ytix[::freq])

plt.tight_layout()
plt.show()

Click to see nicer plot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接