Python 如何将标签添加到箱线图(pylab)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31842892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:38:26  来源:igfitidea点击:

How to add labels to a boxplot figure (pylab)

pythonmatplotlibboxplotaxis-labels

提问by mkpappu

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?

我试过了pylab.xlabel('x')plt.xlable('x')但那些不起作用......?它们是否不适用于箱线图,还是我对这些线的工作有误解?

采纳答案by The Brofessor

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

在此处输入图片说明

回答by tnknepp

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

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

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