1

I have a data frame df that looks like this:

             DateTime  code  value
0 2021-03-25 16:35:49     1   29.0
1 2021-03-25 16:35:49     2   15.0
2 2021-03-25 16:36:09     1   15.0
3 2021-03-25 16:36:09     2   29.0
4 2021-03-25 16:36:51     1   29.0
...

I'd like to make a lineplot of the values with confidence intervals, where the signals are grouped by week. This should be really easy to do with seaborn, but seaborn doesn't seem to allow Period datatypes as values for the x-axis. Running this gives an Invalid object type error:

df['week'] = df.DateTime.dt.to_period('W')
sns.lineplot(data=df, x='week', y='value', hue='code', ci='sd')

I can change the datatype to a timestamp and plot:

df['week'] = df.DateTime.dt.to_period('W')
df.week = df.week.dt.to_timestamp()
sns.lineplot(data=df, x='week', y='value', hue='code', ci='sd')

Line plot with confidence intervals in seaborn, but ugly xaxis labels

This gives me close to what I want, but I'd rather have the x-axis label look like it would if I had plotted it directly with matplotlib. But I can't figure out an easy way to plot the confidence intervals filled in as they are in the seaborn plot.

df['week'] = df.DateTime.dt.to_period('W')
df_week = df.groupby(['week','code'])['value'].agg(['mean']).reset_index()
ax = df_week .query("code==1").plot(x='week', y='mean', label='1')
df_week.query("code==2").plot(ax=ax, x='week', y='mean', label='2')

Means plotted directly from dataframe with nice-looking x-axis labels, but no confidence interval

How can I easily get the plot from the first figure, but with the nice-looking x-axis labels from the second?

BigBen
  • 46,229
  • 7
  • 24
  • 40
  • "look like it would if I had plotted it directly with matplotlib"... well you're actually plotting it with pandas (using matplotlib under the hood), which is doing the xlabel formatting. – BigBen Sep 23 '22 at 20:21
  • Ah, you are right. Is there a way to export the xlabel formatting from one plot to another? – problematic_thematic Sep 23 '22 at 20:24
  • `fill_between` with alpha option will fill like sns package, but you would need to calculate the std yourself. – Quang Hoang Sep 23 '22 at 20:29
  • I don't think this is a duplicate; it's asking about a `Period` dtype which is going to have a different solution from regular `datetime` (which matplotlib can handle natively with its own converters). – mwaskom Sep 23 '22 at 21:39

0 Answers0