Issue
I have my two graphs on top of each other and I would like to put them next to each other but I don't know how to do it?
code :
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'])
Solution
- Convert the columns to a long form with
.melt
- See
seaborn.boxenplot
- Plot by specifying one axis for the values and the other for the category column.
hue=
can be used to visualize a third categorical column.
- Plot by specifying one axis for the values and the other for the category column.
- No legend is required (for this case) because the labels for each are on the axis, so having a legend it redundant
- The categorical axis labels can be changed in a number of ways.
- Tested in
python 3.9.7
,pandas 1.3.4
,matplotlib 3.5.0
,seaborn 0.11.2
dfm = expeditions[["nbre_members", "hired_staff"]].melt()
sns.boxenplot(data=dfm, x='value', y='variable')
Working Example
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')
p.set_yticklabels(['Total Bill', 'Tips'])
plt.show()
Given a 3rd column
- This option uses a 3rd column for
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()
Answered By - Trenton McKinney
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.