9

This is a pretty basic question I'm sure but I cannot seem to find the right code. There is my code for the boxplot I am creating. I would like to label the axes and have a title.

from pylab import *
import numpy
raw_data = list(numpy.genfromtxt(filename, delimiter=','))
print raw_data
figure()
boxplot(raw_data,1)
savefig('testfigure.pdf')

I have tried pylab.xlabel('x') and plt.xlable('x') but those do not work...? Do they not work for boxplots or have I just got it wrong about those lines working?

mkpappu
  • 358
  • 1
  • 3
  • 16

2 Answers2

16

Try this:

import matplotlib.pyplot as plt
from pylab import *

# fake up some data
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# figure related code
fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

ax = fig.add_subplot(111)
ax.boxplot(data)

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

plt.show()

EDIT: Picture

enter image description here

The Brofessor
  • 1,008
  • 6
  • 15
  • Note that, as of version 3.2.1 of Matplotlib, you can specify xlabels directly through [boxplot](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.boxplot.html#matplotlib-pyplot-boxplot) argument `labels`, which must be a list of length compatible with the dimensions of your dataset. – Lith Mar 25 '20 at 09:11
  • @Lith This allows setting tick labels but not axes labels. – Alan May 20 '22 at 17:50
  • @Alan, you are right, thanks. I missed that. – Lith May 24 '22 at 07:16
3

I would recommend explicitly defining your figure window and plot.

from pylab import *
import numpy as np

fig = figure(figsize=(4,4))  # define the figure window
ax  = fig.add_subplot(111)   # define the axis

ax.boxplot(raw_data,1)       # make your boxplot

# add axis texts
ax.set_xlabel('X-label', fontsize=8)
ax.set_ylabel('Y-label', fontsize=8)
ax.set_title('I AM BOXPLOT', fontsize=10)

# format axes
ax.set_xlim([0,100])
ax.set_xticks( np.arange(0,101,10), minor=False)
ax.set_xticks( np.arange(0,100,5),  minor=True)

# if you wish to explicitly set tick labels
ax.set_xticklabels( np.arange(0,101,10), fontsize=8)

# if you wish to explicitly set actual tick parameters
ax.tick_params(axis='both',which='major',direction='in',length=4,width=2,labelsize=8)
ax.tick_params(axis='both',which='minor',direction='in',length=2,width=1.5)  

# and so on...you can do the same for the y-axis.  
# You have quite a lot of control over the axes this way.

another tip, when saving set bbox_inches to 'tight' so you don't cut off your labels

savefig('fig_title.jpg', bbox_inches='tight', dpi=500)
tnknepp
  • 5,888
  • 6
  • 43
  • 57