繁体   English   中英

如何将 plot 多列转换为单个 seaborn boxenplot

[英]How to plot multiple columns into a single seaborn boxenplot

我有两个图表,我想把它们放在一起,但我不知道该怎么做?

代码:

import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
boxenplot_graph = sns.boxenplot(x=expeditions["nbre_members"], color = "r")
boxenplot_graph2 = sns.boxenplot(x=expeditions["hired_staff"],color = "b")
plt.xlabel("Nombre de members/hired_staff")
plt.title("Répartition du nombre de membres/hired_staff")
#plt.gca().legend(('membres', 'morts'))
plt.legend(["members", "hired_staff"],['rouge', 'bleu'])

如果您有两个不同的数据集 expeditions1 和 expeditions2,请使用子图

import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns
expeditions1=np.random.random_integers(1, 100, size=500)
expeditions2=np.random.random_integers(1, 1000, size=500)
sns.set_theme(style="whitegrid")
fig,ax=plt.subplots(2,figsize=(10,10))
boxenplot_graph = sns.boxenplot(y=expeditions1, color = "r",ax=ax[0])
ax[0].set_title("One boxenplot")
boxenplot_graph2 = sns.boxenplot(y=expeditions2,color = "b",ax=ax[1])
plt.xlabel("hired staff")
ax[1].set_title("Two boxenplot")
#plt.gca().legend(('membres', 'morts'))
plt.legend(["members", "hired_staff"],['rouge', 'bleu'])
  • 使用.melt将列转换为长格式
  • seaborn.boxenplot
    • Plot 通过为值指定一个轴,为类别列指定另一个轴。 hue=可用于可视化第三个分类列。
  • 不需要图例(对于这种情况),因为每个标签都在轴上,所以有一个图例是多余的
dfm = expeditions[["nbre_members", "hired_staff"]].melt()
sns.boxenplot(data=dfm, x='value', y='variable')

工作示例

import seaborn as sns
import matplotlib.pyplot as plt

# sample data for wide data
tips = sns.load_dataset('tips')

# display(tips.head(3))
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3

# convert two columns to a long form
dfm = tips[['total_bill', 'tip']].melt()

# display(dfm.head(3))
     variable  value
0  total_bill  16.99
1  total_bill  10.34
2  total_bill  21.01

# plot
fig, ax = plt.subplots(figsize=(6, 4))
p = sns.boxenplot(data=dfm, x='value', y='variable', ax=ax)
p.set(ylabel='My yLabel', xlabel='My xLabel', title='My Title')
plt.show()

在此处输入图像描述

给定第三列

  • 此选项使用第三列表示hue=
# melt columns and have an id variable
dfm = tips[['total_bill', 'tip', 'smoker']].melt(id_vars='smoker')

# display(dfm.head(3))
  smoker    variable  value
0     No  total_bill  16.99
1     No  total_bill  10.34
2     No  total_bill  21.01

# plot
fig, ax = plt.subplots(figsize=(6, 4))
p = sns.boxenplot(data=dfm, x='value', y='variable', hue='smoker', ax=ax)
p.set(ylabel='My yLabel', xlabel='My xLabel')
plt.show()

在此处输入图像描述

暂无
暂无

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

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