【问题标题】:Creating a grouped bar plot with Seaborn使用 Seaborn 创建分组条形图
【发布时间】:2020-11-29 01:34:26
【问题描述】:

我正在尝试使用 Seaborn 创建分组条形图,但我有点迷失在杂草中。我实际上让它工作,但它感觉不像是一个优雅的解决方案。 Seaborn 似乎仅在存在诸如男性/女性之类的二元选项时才支持聚集条形图。 (https://seaborn.pydata.org/examples/grouped_barplot.html)

不得不如此依赖 matplotlib 感觉不对 - 使用子图感觉有点脏:)。有没有办法在 Seaborn 中完全处理这个问题?

谢谢,

安德鲁

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import rcParams
sns.set_theme(style="whitegrid")
rcParams.update({'figure.autolayout': True})

dataframe = pd.read_csv("https://raw.githubusercontent.com/mooperd/uk-towns/master/uk-towns-sample.csv")

dataframe = dataframe.groupby(['nuts_region']).agg({'elevation': ['mean', 'max', 'min'],
                                                   'nuts_region': 'size'}).reset_index()
dataframe.columns = list(map('_'.join, dataframe.columns.values))

# We need to melt our dataframe down into a long format.
tidy = dataframe.melt(id_vars='nuts_region_').rename(columns=str.title)

# Create a subplot. A Subplot makes it convenient to create common layouts of subplots.
# https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html
fig, ax1 = plt.subplots(figsize=(6, 6))

# https://stackoverflow.com/questions/40877135/plotting-two-columns-of-dataframe-in-seaborn
g = sns.barplot(x='Nuts_Region_', y='Value', hue='Variable', data=tidy, ax=ax1)

plt.tight_layout()
plt.xticks(rotation=45, ha="right")
plt.show()

【问题讨论】:

    标签: pandas matplotlib seaborn


    【解决方案1】:

    我不确定你为什么需要去海运。你的数据是宽格式的,所以 pandas 做得很好,不需要融化:

    from matplotlib import rcParams
    sns.set(style="whitegrid")
    rcParams.update({'figure.autolayout': True})
    fig, ax1 = plt.subplots(figsize=(12,6))
    
    dataframe.plot.bar(x='nuts_region_', ax=ax1)
    plt.tight_layout()
    plt.xticks(rotation=45, ha="right")
    plt.show()
    

    输出:

    【讨论】:

    • 很好,谢谢。请问,什么时候去 Seaborn 有用?
    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 2018-10-16
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多