Lineplot doesn't show all dates in axis

為{幸葍}努か 提交于 2019-12-19 10:49:15

问题


I have the followings:

fig, ax = plt.subplots(figsize=(40, 10))
sns.lineplot(x="Date", y="KFQ imports", data=df_dry, color="BLACK", ax=ax)
sns.lineplot(x="Date", y="QRR imports", data=df_dry, color="RED",ax=ax)

ax.set(xlabel="Date", ylabel="Value", )
x_dates = df_dry['Date'].dt.strftime('%b-%Y')
ax.set_xticklabels(labels=x_dates, rotation=45)

Result

When I use a barchart (sns.barplot) the entire spectrum of dates are shown. Am I missing something for the line chart? I


回答1:


The idea would be to set the xticks to exactly the dates in your dataframe. To this end you can use set_xticks(df.Date.values). It might then be good to use a custom formatter for the dates, which would allow to format them in the way you want them.

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

df = pd.DataFrame({"Date" : ["2018-01-22", "2018-04-04", "2018-12-06"],
                   "val"  : [1,2,3]})
df.Date = pd.to_datetime(df.Date)


ax = sns.lineplot(data=df, x="Date", y="val", marker="o")
ax.set(xticks=df.Date.values)
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
plt.show()

Note how the same can be achieved without seaborn, as

ax = df.set_index("Date").plot(x_compat=True, marker="o")
ax.set(xticks=df.Date.values)
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
plt.show()


来源:https://stackoverflow.com/questions/54186083/lineplot-doesnt-show-all-dates-in-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!