两个子图和图例顺序之间的颜色不匹配

问题描述 投票:0回答:3

我正在为我的 Seaborn 箱线图和直方图(绘制为子图)的两个小格式问题而苦苦挣扎。

  1. 两个子图之间的颜色slightly不同,即使编码颜色完全相同。
  2. 我正在尝试重新排列图例的顺序,以便“A 组”出现在“B 组”上方
groupA = [94, 74, 65, 36, 32, 65, 56, 59, 24, 133, 16, 8, 18]
groupB = [1, 1, 1, 1, 2, 7, 7, 10, 15, 16, 17, 17, 19, 29, 31, 32, 43, 43, 44, 47, 56, 64, 64, 80, 81, 87, 103, 121, 121, 121, 187, 197, 236, 292, 319, 8, 12, 12, 14, 14, 15, 16, 16, 20, 20, 33, 36, 37, 37, 44, 46, 48, 51, 51, 54, 57, 72, 74, 95, 103, 103, 107, 134, 199, 216, 228, 254]
f, (ax_boxplot, ax_histogram) = plt.subplots(2, sharex=True, gridspec_kw={'height_ratios': (0.3,0.7)}, figsize=(10,10))
sns.boxplot(data=[groupA, groupB], ax=ax_boxplot, orient='h', palette=['green', 'silver'])
ax_boxplot.tick_params(axis='y', left=False, labelleft=False)
sns.histplot(data=[groupA, groupB], bins=34, binrange=(0,340), palette=['green', 'silver'], alpha=1, edgecolor='black')
ax_histogram.tick_params(axis='both', labelsize=18)
ax_histogram.legend(labels=['groupB', 'groupA'], fontsize=16, frameon=False)
plt.xlabel("Days", fontsize=24, labelpad=20)
plt.ylabel("Count", fontsize=24, labelpad=20)
sns.despine()

到目前为止我尝试了什么:

  • 对于颜色:我尝试在直方图中将 alpha 设置为 1,但似乎仍然存在细微差异。
  • 对于图例:尝试使用 hue_order 和句柄,但没有任何运气让它起作用。

Image of histogram and boxplot subplots

python seaborn boxplot subplot histplot
3个回答
2
投票

尝试在拨打

saturation=1
时使用
boxplot
。除非特别说明,否则饱和度等于
0.75
.

文档说:

饱和浮点数,可选

绘制颜色的原始饱和度比例。大块通常看起来颜色稍微不饱和,但如果您希望绘图颜色与输入颜色完美匹配,请将此设置为 1。


2
投票

您的着色问题在 StackOverflow 上很常见。例如。 避免 Seaborn barplot 颜色去饱和Seaborn 图表颜色与调色板指定的颜色不同自定义 seaborn 调色板的颜色不一致。 Seaborn 的作者喜欢矩形的去饱和颜色,所以默认启用。

Seaborn 创建了自己的图例,这些图例通常与您调用 matplotlib 的

ax.legend(...)
得到的图例不同。为了改变图例的参数,Seaborn 有一个
sns.move_legend()
函数。
move_legend
主要是为了改变位置,但你也可以改变其他参数(除了项目标签)。由于“新”位置是必需的参数,您可以使用默认的
loc='best'

对于图例中的标签,Seaborn 惯用的方式是“长格式”数据框,其中一列用作

hue=
。但是 Seaborn 也支持像
data
这样的字典。然后,字典的标签作为图例标签。

请注意,除非您添加

sns.histplot(..., multiple='stack')
(或
multiple='dodge'
),否则最后绘制的直方图的条形图将(部分或全部)隐藏另一个直方图的条形图。这可能非常令人困惑(这就是为什么默认设置了一些透明度)。

import matplotlib.pyplot as plt
import seaborn as sns

groupA = [94, 74, 65, 36, 32, 65, 56, 59, 24, 133, 16, 8, 18]
groupB = [1, 1, 1, 1, 2, 7, 7, 10, 15, 16, 17, 17, 19, 29, 31, 32, 43, 43, 44, 47, 56, 64, 64, 80, 81, 87, 103, 121, 121, 121, 187, 197, 236, 292, 319, 8, 12, 12, 14, 14, 15, 16, 16, 20, 20, 33, 36, 37, 37, 44, 46, 48, 51, 51, 54, 57, 72, 74, 95, 103, 103, 107, 134, 199, 216, 228, 254]
f, (ax_boxplot, ax_histogram) = plt.subplots(2, sharex=True,
                                             gridspec_kw={'height_ratios': (0.3, 0.7)}, figsize=(10, 10))

sns.boxplot(data=[groupA, groupB], ax=ax_boxplot, orient='h',
            palette=['green', 'silver'], saturation=1)
ax_boxplot.tick_params(axis='y', left=False, labelleft=False)

sns.histplot(data={'Group A': groupA, 'Group B': groupB},
             bins=34, binrange=(0, 340),
             palette=['green', 'silver'], alpha=1, edgecolor='black')
ax_histogram.tick_params(axis='both', labelsize=18)
ax_histogram.set_xlabel("Days", fontsize=24, labelpad=20)
ax_histogram.set_ylabel("Count", fontsize=24, labelpad=20)
sns.move_legend(ax_histogram, loc='best', fontsize=24, frameon=False)
sns.despine()

plt.show()


0
投票
  • @JohanC所述,将数据放入长格式数据框的好处是允许
    seaborn
    自动添加标签,并处理订单。
  • pd.DataFrame(data=v, columns=['Days']).assign(Group=group)
    用于为每个列表创建一个数据框,其中
    .assign
    为数据名称创建一个名为
    'Group'
    的列。这两个数据框结合
    pd.concat
    .
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# set the matplotlib rc parameters (global settting)
params = {'axes.labelsize': 24,
          'axes.titlesize': 24,
          'axes.labelpad': 20,
          'axes.spines.top': False,
          'axes.spines.right': False,
          'ytick.labelsize': 18,
          'xtick.labelsize': 18,
          'legend.fontsize': 20,
          'legend.frameon': False,
          'legend.title_fontsize': 16}

plt.rcParams.update(params)

# create the dataframe with a column defining the groups
df = pd.concat([pd.DataFrame(data=v, columns=['Days']).assign(Group=group) for v, group in zip([groupA, groupB], ['A', 'B'])])

# create the figure and axes
fig, (ax_boxplot, ax_histogram) = plt.subplots(2, sharex=True, gridspec_kw={'height_ratios': (0.3,0.7)}, figsize=(10,10))

# plot the histplot from df
sns.histplot(data=df, x='Days', hue='Group', bins=34, binrange=(0,340), palette=['green', 'silver'], alpha=1, edgecolor='black', ax=ax_histogram)

# plot the boxplot from df
sns.boxplot(data=df, x='Days', y='Group', ax=ax_boxplot, palette=['green', 'silver'])
ax_boxplot.tick_params(axis='y', left=False, labelleft=False, bottom=False)
_ = ax_boxplot.set(xlabel='', ylabel='')

df.head(15)

    Days Group
0     94     A
1     74     A
2     65     A
3     36     A
4     32     A
5     65     A
6     56     A
7     59     A
8     24     A
9    133     A
10    16     A
11     8     A
12    18     A
0      1     B
1      1     B
© www.soinside.com 2019 - 2024. All rights reserved.