seaborn情节总计

时间:2017-07-18 10:02:42

标签: python matplotlib visualization seaborn

我有以下数据框:

df = pd.DataFrame({'group': ['Red', 'Red', 'Red', 'Blue', 'Blue', 'Blue'],
                   'valueA_found': [10, 40, 50, 20, 50, 70],
                   'valueA_total': [100,200, 210, 100, 200, 210],
                  'date': ['2017-01-01', '2017-02-01', '2017-03-01', '2017-01-01', '2017-02-01', '2017-03-01']})

并且可以创建一个情节:

fig, ax = plt.subplots(figsize=(15,8))
sns.set_style("whitegrid")
g = sns.barplot(x="date", y="valueA_found", hue="group", data=df)
# g.set_yscale('log')
g.set_xticklabels(df.date, rotation=45)
g.set(xlabel='date', ylabel='value from total')

但是,我希望每个时间点都能看到以下内容: enter image description here 正如您所看到的,每个模型的值将A_found绘制为条形,并将总数绘制为单个条形。

最初建议,也可以将总数绘制为一条线 - 但正如评论中所述,生产条形图可能更好。 valueA_total即每个组每月的总数应该相同。

1 个答案:

答案 0 :(得分:2)

选项可能是在第一个数据集后面的去饱和/更透明条形图中绘制总值。

import matplotlib.pyplot as plt
import pandas as pd
import seaborn.apionly as sns

df = pd.DataFrame({'group': ['Red', 'Red', 'Red', 'Blue', 'Blue', 'Blue'],
                   'valueA': [10, 40, 50, 20, 50, 70],
                   'valueB': [100,200, 210, 100, 200, 210],
                  'date': ['2017-01-01', '2017-02-01', '2017-03-01', 
                           '2017-01-01', '2017-02-01', '2017-03-01']})

fig, ax = plt.subplots(figsize=(6,4))

sns.barplot(x="date", y="valueB", hue="group", data=df, 
            ax=ax, palette={"Red":"#f3c4c4","Blue":"#c5d6f2" }, alpha=0.6)
sns.barplot(x="date", y="valueA", hue="group", data=df, 
            ax=ax, palette={"Red":"#d40000","Blue":"#0044aa" })


ax.set_xticklabels(df.date, rotation=45)
ax.set(xlabel='date', ylabel='value from total')

plt.show()

enter image description here

或者只是在背景中放置一个条形图,假设每组的总数始终相同:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn.apionly as sns

df = pd.DataFrame({'group': ['Red', 'Red', 'Red', 'Blue', 'Blue', 'Blue'],
                   'valueA': [10, 40, 50, 20, 50, 70],
                   'valueB': [100,200, 210, 100, 200, 210],
                  'date': ['2017-01-01', '2017-02-01', '2017-03-01', 
                           '2017-01-01', '2017-02-01', '2017-03-01']})

fig, ax = plt.subplots(figsize=(6,4))

sns.barplot(x="date", y="valueB", data=df[df.group=="Red"], 
            ax=ax,  color="#e7e2e8", label="total")
sns.barplot(x="date", y="valueA", hue="group", data=df, 
            ax=ax, palette={"Red":"#d40000","Blue":"#0044aa" })


ax.set_xticklabels(df.date, rotation=45)
ax.set(xlabel='date', ylabel='value from total')

plt.show()

enter image description here