Issue
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)
When I use a barchart (sns.barplot
) the entire spectrum of dates are shown. Am I missing something for the line chart? I
Solution
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()
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.