How do I manually set the max value for the Y axis in my pandas boxplot?

877 views Asked by At

I'm looking at this official Pandas documentation, which says I can specify an "object of class matplotlib.axes.Axes" when creating my boxplot.

How do I format this boxplot axis object so that I can manually set the maximum Y axis value?

I've seen questions and answers on here relating to changing the Y axis after the boxplot is created, but those have not worked for me and I'd like to set the Y axis max at the time of the boxplot's creation.

This is the code I have so far:

import pandas as pd    
prices= pd.read_csv('..\priceData.csv')
boxplot = prices.boxplot(column=['price'])
2

There are 2 answers

5
Corralien On

Get the Axes returned by boxplot and use:

xmin, xmax = [-5, 5]
ymin, ymax = [-5, 5]

boxplot = prices.boxplot(column=['price'])
boxplot.set_xlim([xmin, xmax])
boxplot.set_ylim([ymin, ymax])

boxplot from the documentation:

import pandas as pd
import numpy as np

np.random.seed(1234)

df = pd.DataFrame(np.random.randn(10, 4),
                  columns=['Col1', 'Col2', 'Col3', 'Col4'])
boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3'])

enter image description here

After set_xlim and set_ylim:

enter image description here

0
Trenton McKinney On
  • The correct way is to use the ylim and xlim parameters.
  • pandas.DataFrame.plot shows the full set of parameters available in pandas.DataFrame.boxplot.
  • When using Jupyter, ax. methods must be in the same cell as the plot call ax = df.plot(...).
  • Tested in python 3.11, pandas 1.5.3, matplotlib 3.7.0
import pandas as pd
import numpy as np

np.random.seed(2023)
df = pd.DataFrame(np.random.randn(10, 4), columns=['Col1', 'Col2', 'Col3', 'Col4'])

ax = df.plot(kind='box', ylim=(-5, 5))

enter image description here

  • Use the yticks and xticks parameters to specify ticks.
ax = df.plot(kind='box', ylim=(-5, 5), yticks=range(-5, 6))

# or only use the following without ylim
ax = df.plot(kind='box', yticks=range(-5, 6))

enter image description here