Seaborn - 根据 x 名称而不是色调更改条形颜色? [英] Seaborn - change bar color according to x name instead of hue?

查看:67
本文介绍了Seaborn - 根据 x 名称而不是色调更改条形颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

将 seaborn 导入为 sns将熊猫导入为 pd导入 matplotlib.pyplot 作为 pltsns.set_style('darkgrid')图, ax = plt.subplots()a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],'场景': ['X', 'Y', 'X', 'Y', 'X', 'Y'],'持续时间':[4, 3, 5, 4, 9, 7]})g = sns.barplot(data=a, x='Scenario', y='Duration',色调='程序',ci = 无)

我希望 x=Xx=Y 有不同的颜色,但每个色调(A, B, Total ...) 的颜色相同.(可能有比两个更多的场景).如何根据 x 名称而不是色调更改条形颜色?

解决方案

我不知道使用 sns.barplot 设置颜色的任何直接方法.以下是如何使用

For example:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_style('darkgrid')
fig, ax = plt.subplots()

a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})

g = sns.barplot(data=a, x='Scenario', y='Duration',
                hue='Program', ci=None)

I want x=X and x=Y have different color, but same color for each hue(A, B, Total ...) . ( There may be more Scenario than two ) . How do I change bar color according to x name instead of hue ?

解决方案

I am not aware of any straightforward way to set the colors like that using sns.barplot. Here is how can do this using pandas instead:

import pandas as pd    # v 1.1.3
import seaborn as sns  # v 0.11.0
sns.set_style('darkgrid')

# Create sample dataset
a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})

# Pivot table and plot data in a bar chart
a_pivot = a.pivot(index='Scenario', columns='Program')
ax = a_pivot.plot.bar(color=[['tab:blue', 'tab:orange']], rot=0,
                      legend=None, figsize=(8,5))

# Format labels and ticks
ax.set_xlabel('Scenario', labelpad=10, size=14)
ax.set_ylabel('Duration', labelpad=20, size=14)
ax.tick_params(axis='both', labelsize=12)

这篇关于Seaborn - 根据 x 名称而不是色调更改条形颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆