yongsheng
yongsheng

Reputation: 396

How to show multiple timeseries plots using seaborn

I'm trying to generate 4 plots from a DataFrame using Seaborn

Date        A       B       C       D
2019-04-05  330.665 161.975 168.69  0
2019-04-06  322.782 150.243 172.539 0
2019-04-07  322.782 150.243 172.539 0
2019-04-08  295.918 127.801 168.117 0
2019-04-09  282.674 126.894 155.78  0
2019-04-10  293.818 133.413 160.405 0

I have casted dates using pd.to_DateTime and numbers using pd.to_numeric. Here is the df.info():

<class 'pandas.core.frame.DataFrame'>
Int64Index: 6 entries, 460 to 465
Data columns (total 5 columns):
Date  6 non-null datetime64[ns]
A     6 non-null float64
B     6 non-null float64
C     6 non-null float64
D     6 non-null float64
dtypes: datetime64[ns](1), float64(4)
memory usage: 288.0 bytes

I can do a wide column plot by just calling .plot() on df.

However,

  1. The legend of the plot is covering the plot itself

  2. I would instead like to have 4 separate plots in 1 diagram and have tried using lmplot to achieve this.

  3. I would like to add labels to the plot like so:

    Plot with image

I first melted the data:

df=pd.melt(df,id_vars='Date', var_name='Var', value_name='Unit')

And then tried lmplot

sns.lmplot(x = df['Date'], y='Unit', col='Var', data=df)

However, I get the traceback:

TypeError: Invalid comparison between dtype=datetime64[ns] and str

I have also tried setting df.set_index['Date'] and replotting that using x=df.index and that gave me the same error.

The data can be plotted using Google Sheets but I am trying to automate a workflow where the chart can be generated and sent via Slack to selected recipients.

I hope I have expressed myself clearly enough as I am rather new to Python and Seaborn and hope to get some help from the experts here.

Upvotes: 0

Views: 330

Answers (1)

rpanai
rpanai

Reputation: 13437

Regarding the legend you can just use .legend(loc="upper left", bbox_to_anchor=(1,1)) as in this example

%matplotlib inline
import pandas as pd
import numpy as np


data = np.random.rand(10,4)
df = pd.DataFrame(data, columns=["A", "B", "C", "D"])
df.plot()\
  .legend(loc="upper left", bbox_to_anchor=(1,1));

While for the second IIUC you can play from

df.plot(subplots=True, layout=(2,2));

Upvotes: 1

Related Questions