简体   繁体   中英

Seaborn figure with multiple axis (year) and month on x-axis

I try to become warm with seaborn. I want to create one or both of that figures (bar plot & line plot). You see 12 months on the X-axis and 3 years each one with its own line or bar color.

在此处输入图像描述

That is the data creating script including the data in comments.

#!/usr/bin/env python3
import random as rd
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns

rd.seed(0)

a = pd.DataFrame({
    'Y': [2016]*12 + [2017]*12 + [2018]*12,
    'M': list(range(1, 13)) * 3,
    'n': rd.choices(range(100), k=36)
})
print(a)

#        Y   M   n
# 0   2016   1  84
# 1   2016   2  75
# 2   2016   3  42
# ...
# 21  2017  10  72
# 22  2017  11  89
# 23  2017  12  68
# 24  2018   1  47
# 25  2018   2  10
# ...
# 34  2018  11  54
# 35  2018  12   1


b = a.pivot_table(columns='M', index='Y')
print(b)
#        n
# M     1   2   3   4   5   6   7   8   9   10  11  12
# Y
# 2016  84  75  42  25  51  40  78  30  47  58  90  50
# 2017  28  75  61  25  90  98  81  90  31  72  89  68
# 2018  47  10  43  61  91  96  47  86  26  80  54   1

I'm even not sure which form ( a or b or something elese) of a dataframe I should use here.

What I tried

I assume in seaboarn speech it is a countplot() I want. Maybe I am wrong?

>>> sns.countplot(data=a)
<AxesSubplot:ylabel='count'>
>>> plt.show()

The result is senseless在此处输入图像描述

I don't know how I could add the pivoted dataframe b to seaborn.

You could do the first plot with a relplot , using hue as a categorical grouping variable:

sns.relplot(data=a, x='M', y='n', hue='Y', kind='line')

I'd use these colour and size settings to make it more similar to the plot you wanted:

sns.relplot(data=a, x='M', y='n', hue='Y', kind='line', palette='pastel', height=3, aspect=3)

在此处输入图像描述

The equivalent axes-level code would be sns.lineplot(data=a, x='M', y='n', hue='Y', palette='pastel')

Your second can be done with catplot :

sns.catplot(kind='bar', data=a, x='M', y='n', hue='Y')

Or the axes-level function sns.barplot . In that case let's move the default legend location:

sns.barplot(data=a, x='M', y='n', hue='Y')
plt.legend(bbox_to_anchor=(1.05, 1))

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM