简体   繁体   English

如何使用 Seaborn 在同一图上绘制多个直方图

[英]How To Plot Multiple Histograms On Same Plot With Seaborn

With matplotlib, I can make a histogram with two datasets on one plot (one next to the other, not overlay).使用 matplotlib,我可以在一个图上使用两个数据集制作直方图(一个挨着另一个,而不是重叠)。

import matplotlib.pyplot as plt
import random

x = [random.randrange(100) for i in range(100)]
y = [random.randrange(100) for i in range(100)]
plt.hist([x, y])
plt.show()

This yields the following plot.这产生了以下情节。

在此处输入图片说明

However, when I try to do this with seabron;但是,当我尝试使用 seabron 执行此操作时;

import seaborn as sns
sns.distplot([x, y])

I get the following error:我收到以下错误:

ValueError: color kwarg must have one color per dataset

So then I try to add some color values:那么我尝试添加一些颜色值:

sns.distplot([x, y], color=['r', 'b'])

And I get the same error.我得到了同样的错误。 I saw this post on how to overlay graphs, but I would like these histograms to be side by side, not overlay.我看到这篇关于如何叠加图形的帖子,但我希望这些直方图并排放置,而不是叠加。

And looking at the docs it doesn't specify how to include a list of lists as the first argument 'a'.查看文档,它没有指定如何将列表列表包含为第一个参数“a”。

How can I achieve this style of histogram using seaborn?如何使用 seaborn 实现这种直方图风格?

If I understand you correctly you may want to try something this:如果我理解正确,您可能想尝试以下操作:

fig, ax = plt.subplots()
for a in [x, y]:
    sns.distplot(a, bins=range(1, 110, 10), ax=ax, kde=False)
ax.set_xlim([0, 100])

Which should yield a plot like this:这应该产生这样的情节:

在此处输入图片说明

UPDATE :更新

Looks like you want 'seaborn look' rather than seaborn plotting functionality.看起来您想要“seaborn 外观”而不是 seaborn 绘图功能。 For this you only need to:为此,您只需要:

import seaborn as sns
plt.hist([x, y], color=['r','b'], alpha=0.5)

Which will produce:这将产生:

在此处输入图片说明

Merge x and y to DataFrame, then use histplot with multiple='dodge' and hue option:将 x 和 y 合并到 DataFrame,然后使用带有 multiple='dodge' 和 Hue 选项的 histplot:

import matplotlib.pyplot as plt
import pandas as pd
import random

x = [random.randrange(100) for i in range(100)]
y = [random.randrange(100) for i in range(100)]
df = pd.concat(axis=0, ignore_index=True, objs=[
    pd.DataFrame.from_dict({'value': x, 'name': 'x'}),
    pd.DataFrame.from_dict({'value': y, 'name': 'y'})
])
fig, ax = plt.subplots()
sns.histplot(data=df, x='value', hue='name', multiple='dodge', bins=range(1, 110, 10), ax=ax)
ax.set_xlim([0, 100])

Here is the plot result.这是绘图结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM