如何在boxplot图中添加标签(pylab)

时间:2015-08-05 21:10:59

标签: python matplotlib boxplot axis-labels

这是一个非常基本的问题,我确定,但我似乎找不到合适的代码。 我正在创建的boxplot有我的代码。我想标记轴并有标题。

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

我已经尝试了pylab.xlabel('x')plt.xlable('x'),但那些不起作用......?他们不是为箱形图工作,还是我对那些工作线路做错了?

2 个答案:

答案 0 :(得分:9)

试试这个:

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()

编辑:图片

enter image description here

答案 1 :(得分:1)

我建议明确定义你的数字窗口和情节。

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.

另一个提示,将bbox_inches设置为'tight',这样就不会切断标签

savefig('fig_title.jpg', bbox_inches='tight', dpi=500)