失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python 柱状图宽度设置_Python matplotlib 柱状图实例

python 柱状图宽度设置_Python matplotlib 柱状图实例

时间:2024-04-13 02:57:11

相关推荐

python 柱状图宽度设置_Python matplotlib 柱状图实例

学习用matplotlib绘图中,数据是我之前做的实验,隐去了关键信息。

出来的效果就是题图这样,基本可以满足柱状图的绘图要求。

完整代码及注释如下:

import numpy as np

import matplotlib.pyplot as plt

#解决显示不出中文的问题

from pylab import *

mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体

mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题

n_groups = 3 #几组数据

#三组数据中每组2个数据

means_men = (433.147, 452.569,444.969 )

std_men = (42.606, 39.889, 45.779)

means_women = (503.508, 552.544,539.922)

std_women = (43.549,53.917,43.131)

fig, ax = plt.subplots() #这个设置用于后面在每个主题上显示数值

#设置索引和柱体宽度

index = np.arange(n_groups)

bar_width = 0.4

#不透明度和error bar的颜色

opacity = 0.4

error_config = {'ecolor': '0.3'}

#每组数据的设置

rects1 = plt.bar(index, means_men, bar_width,

alpha=opacity, #alpha :float (0.0 transparent through 1.0 opaque)

color='b',

yerr=std_men,

error_kw=error_config, #error bar

label='男') #每组数据中每个数据的标签

rects2 = plt.bar(index + bar_width, means_women, bar_width, #注意 index+bar_width

alpha=opacity,

color='r',

yerr=std_women,

error_kw=error_config,

label='女')

#设置柱体上显示数据值

def autolabel(rects):

# attach some text labels

for rect in rects:

height = rect.get_height()

ax.text(rect.get_x()+rect.get_width()/2.0, 1.1*height,

'%.2f'%float(height), ha='center', va='bottom')

#‘%.2f’%float(height)这个设置是让显示的数值精度为小数点后两位小数

autolabel(rects1)

autolabel(rects2)

plt.xlabel('x轴')

plt.ylabel('y轴')

plt.title('图表标题')

plt.xticks(index + bar_width / 2, ("a组", 'b组', 'c组'))

plt.ylim(0,1000) #设置y轴的标尺

plt.xlim(-0.5,3) #设置x轴的标尺

plt.legend()

fig.savefig('图片名称.png',dpi=600) #保存图片并设置分辨率

基本上是从网上按需求查找并整理出来的,作为记录使用。

如果觉得《python 柱状图宽度设置_Python matplotlib 柱状图实例》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。