324
324

Reputation: 724

Comparative Boxplot in Python

I have a pandas dataframe similar to the following

names   
x     3.5
x     3.7
z     2.8
x     3.4
y     3.25
z     2.9
...

And I wish to make a comparative boxplot (three boxplots next to each other for each of x, y, and z. I'm using the seaborn package, and I can only get a boxplot for all of the values combined. What am I doing wrong?

b = sns.boxplot(data = dat);

Upvotes: 0

Views: 2570

Answers (1)

Lerner Zhang
Lerner Zhang

Reputation: 7150

I think you can draw the side by side boxplot this way:

import pandas as pd
import seaborn as sns
from io import StringIO
data = """
names,num
x,3.5
x,3.7
z,2.8
x,3.4
y,3.25
z,2.9
"""
df = pd.read_csv(StringIO(data), header=0)
to_replace = {0:'x', 1:'y', 2:'z'}
df['names'] = df['names'].replace(to_replace=to_replace)
order = ["x", "y", "z"]
sns.boxplot(x="names", y="num", data=df, order=order)

Here is the boxplot:

enter image description here

Refs:

  1. How to use Python Seaborn for Exploratory Data Analysis

Upvotes: 1

Related Questions