I have some problems with the x-axis values of a seaborn line-plot:
import pandas as pd
import seaborn as sns
# data
df = pd.DataFrame(columns=['calendar_week', 'product_name', 'value'],
data=[['201850', 'product01', 1], ['201905', 'product01', 10], ['201910', 'product01', 7],
['201840', 'product02', 4], ['201911', 'product02', 9], ['201917', 'product02', 17], ['201918', 'product02', 12]])
# plot
sns.lineplot(data=df, x='calendar_week', y='value', hue='product_name');
If the calendar_week values are strings, it plots the second graph after the first one. If the calendar_week values are integers, it fills the data from 201852 to 201899 automatically. What's the best way to plot both graphs on one sorted x-axis with only the given calendar_week values?
Here is the plot with calendar_week as string:
Here is the plot with calendar_week as int:
Thanks for help.
It's a bit roundabout, but I think you need first to convert your week numbers into real dates, plot, then use a custom formater on the x-axis to show the week number again.
df = pd.DataFrame(columns=['calendar_week', 'product_name', 'value'],
data=[['201850', 'product01', 1], ['201905', 'product01', 10], ['201910', 'product01', 7],
['201840', 'product02', 4], ['201911', 'product02', 9], ['201917', 'product02', 17], ['201918', 'product02', 12]])
df['date'] = pd.to_datetime(df.calendar_week+'0', format='%Y%W%w')
# plot
fig, ax = plt.subplots()
sns.lineplot(data=df, x='date', y='value', hue='product_name', ax=ax)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%W"))
fig.autofmt_xdate()
I'm from Germany and I have to deal with ISO weeks, so I ended up doing this:
import pandas as pd
import seaborn as sns
import datetime
import matplotlib
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# data
df = pd.DataFrame(columns=['calendar_week', 'product_name', 'value'],
data=[['201850', 'product01', 1], ['201905', 'product01', 10], ['201910', 'product01', 7],
['201840', 'product02', 4], ['201911', 'product02', 9], ['201917', 'product02', 17], ['201918', 'product02', 12]])
# convert calendar weeks to date
df['date'] = df['calendar_week'].apply(lambda x: datetime.datetime.strptime(x + '-1', '%G%V-%u'))
# plot
fig, ax = plt.subplots()
sns.lineplot(data=df, x='date', y='value', hue='product_name', ax=ax)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%G%V'))
fig.autofmt_xdate()
plt.show();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.