[英]The most elegant way to modify messy and overlapping date labels below x axis? (Seaborn, barplot)
我會同時做:旋轉你的 xlabels 並只使用日期:
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()
這會自動調整 SNS 繪圖的日期 x 軸,因此在大多數情況下您不必手動執行此操作: sns_plot.get_figure().autofmt_xdate()
另一種解決方案,如果您有大量日期並且希望以更稀疏的間隔標記它們;
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 繪圖默認值,並將日期放在 yaxis 上以方便閱讀,但這更多是個人喜好。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.