![](/img/trans.png)
[英]Generating a Line Graph using Seaborn or Matplotlib with: Year as hue, Month as X-Axis and Float Column as Y-Axis
[英]Seaborn figure with multiple axis (year) and month on x-axis
我試着用 seaborn 變得溫暖。 我想創建一個或兩個數字(條形圖 plot 和線圖)。 您在 X 軸上看到 12 個月和 3 年,每個月都有自己的線條或條形顏色。
那是數據創建腳本,包括注釋中的數據。
#!/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
我什至不確定我應該在這里使用 dataframe 的哪種形式( a
或b
或其他)。
我假設在 seaboarn 演講中它是我想要的countplot()
。 也許我錯了?
>>> sns.countplot(data=a)
<AxesSubplot:ylabel='count'>
>>> plt.show()
我不知道如何將旋轉的 dataframe b
添加到 seaborn。
您可以使用 relplot 執行第一個relplot
,使用hue
作為分類分組變量:
sns.relplot(data=a, x='M', y='n', hue='Y', kind='line')
我會使用這些顏色和尺寸設置使其更類似於您想要的 plot:
sns.relplot(data=a, x='M', y='n', hue='Y', kind='line', palette='pastel', height=3, aspect=3)
等效的軸級代碼是sns.lineplot(data=a, x='M', y='n', hue='Y', palette='pastel')
你的第二個可以用catplot
完成:
sns.catplot(kind='bar', data=a, x='M', y='n', hue='Y')
或軸級 function sns.barplot
。 在這種情況下,讓我們移動默認的圖例位置:
sns.barplot(data=a, x='M', y='n', hue='Y')
plt.legend(bbox_to_anchor=(1.05, 1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.