Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas boxplot, groupby different ylim in each subplot

I have a dataframe and I would like to plot it as:

>>> X = pd.DataFrame(np.random.normal(0, 1, (100, 3)))
>>> X['NCP'] = np.random.randint(0, 5, 100)
>>> X[X['NCP'] == 0] += 100
>>> X.groupby('NCP').boxplot()

The result is what I want but all the subplots have the same ylim. This makes impossible to visualize the result properly. How can I set different ylim for each subplot?

like image 434
Donbeo Avatar asked Mar 31 '26 10:03

Donbeo


1 Answers

What you asked for was to set the y axis separately for each axes. I believe that should be ax.set_ylim([a, b]). But every time I ran it for each axes it updated for all.

Because I couldn't figure out how to answer your question directly, I'm providing a work around.

X = pd.DataFrame(np.random.normal(0, 1, (100, 3)))
X['NCP'] = np.random.randint(0, 5, 100)
X[X['NCP'] == 0] += 100

groups = X.groupby('NCP')

print groups.groups.keys()

# This gets a number of subplots equal to the number of groups in a single 
# column.  you can adjust this yourself if you need.
fig, axes = plt.subplots(len(groups.groups), 1, figsize=[10, 12])

# Loop through each group and plot boxplot to appropriate axis
for i, k in enumerate(groups.groups.keys()):
    group = groups.get_group(k)
    group.boxplot(ax=axes[i], return_type='axes')

subplots DOCUMENTATION

like image 105
piRSquared Avatar answered Apr 03 '26 02:04

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!