seaborn- matplotlib.pyplot – boxplot – how to provide bins on the axis and add axis labels or sub-titles to sub-plots?

Question:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
import warnings

df = pd.DataFrame([[0.2,40,1], [0.4,50,6], [5,14,5],
                   [1,25,7], [9,23,4], [3,300,100]],
                  columns=['a1', 'a2', 'a3'])

fig, axes = plt.subplots(nrows=3, ncols=1,figsize=(18, 10), sharex=False)

sns.boxplot(ax=axes[0],data=df,y="a1")

sns.boxplot(ax=axes[1],data=df,y="a2")

sns.boxplot(ax=axes[2],data=df,y="a3")

I have found ways to put limits, for instance – set(xlim=(0,15),ylim=(0,100)))
However, this isn’t what I’m looking for, I’d like to have a handle on the y-axis in this data. For example – y-axis for a3 – 0, 35, 60, 100

Further, how do I set/change y-axis labels, or add sub-titles to each of grid-plots?

Asked By: Death Metal

||

Answers:

If I understood your question correctly, you want to show specific tick labels for y-axis. To set this, you can use set_yticks() and provide the tick labels you want to show. For giving individual y-axis labels for each subplot, use axis set_ylabel(). Similarly, you can use axis set_title() to set individual axis title. Updated code below.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
import warnings
df = pd.DataFrame([[0.2,40,1], [0.4,50,6], [5,14,5], [1,25,7], [9,23,4], [3,300,100]], columns=['a1', 'a2', 'a3'])
fig, axes = plt.subplots(nrows=3, ncols=1,figsize=(4, 10), sharex=False)
sns.boxplot(ax=axes[0],data=df,y="a1")
axes[0].set_yticks([0,0.5,5,10])
axes[0].set_ylabel('My A1 Label')
axes[0].set_title('My A1 Title')

sns.boxplot(ax=axes[1],data=df,y="a2")
axes[1].set_yticks([0,100,250,300])
axes[1].set_ylabel('My A2 Label')
axes[1].set_title('My A2 Title')

sns.boxplot(ax=axes[2],data=df,y="a3")
axes[2].set_yticks([0,35,60,100])
axes[2].set_ylabel('My A3 Label')
axes[2].set_title('My A3 Title')

enter image description here

Answered By: Redox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.