【问题标题】:Seaborn - change bar color according to x name instead of hue?Seaborn - 根据x名称而不是色调更改条形颜色?
【发布时间】:2020-06-23 04:21:08
【问题描述】:

例如:

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)

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

【问题讨论】:

  • palette={"A" : "blue", "B" : "blue", "Total" : "red"}
  • @ImportanceOfBeingErnest 例如,我希望 X 为蓝色,Y 为红色,无论 A、B、Total 。我可以按顺序区分A、B、Total,不需要颜色。

标签: python matplotlib seaborn


【解决方案1】:

我不知道使用sns.barplot 设置颜色的任何直接方法。下面是如何使用pandas 代替:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多