Python matplotlib 柱状图(条形图)官方实例学习

官方示例

# Credit: Josh Hemann

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple

n_groups = 5

means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)

means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {
    
    'ecolor': '0.3'}

rects1 = ax.bar(index, means_men, bar_width,
                alpha=opacity, color='b',
                yerr=std_men, error_kw=error_config,
                label='Men')

rects2 = ax.bar(index + bar_width, means_women, bar_width,
                alpha=opacity, color='r',
                yerr=std_women, error_kw=error_config,
                label='Women')

ax.set_xlabel('Group')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
ax.legend()

fig.tight_layout()
plt.show()

运行结果

在这里插入图片描述

例一

method pointnet pointnet++ DGCNN
A 89.2 90.7 92.2
B 90.9 92.9 93.4
ours 91.3 93.4 93.4

要画三组数据的柱状图,每组数据又分为三个变量,代码基本都标出注释
代码如下(示例):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple

#解决显示不出中文的问题
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体
mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题

n_groups = 3#几组数据

means_1 = (89.2, 90.7,92.2)
means_2 = (90.9,92.9,93.4)
means_3 = (91.3,93.4,93.4)

fig, ax = plt.subplots()#这个设置用于后面在每个主题上显示数值
#设置索引和柱体宽度
index = np.arange(n_groups)
bar_width = 0.25

opacity = 0.4#不透明度

rects1 = ax.bar(index, means_1, bar_width,
                alpha=opacity, #color='b',
                label='Trained with A')

rects2 = ax.bar(index + bar_width, means_2, bar_width,
                alpha=opacity, #color='g',
                label='Trained with B')

rects3 = ax.bar(index + bar_width + bar_width, means_3, bar_width,
                alpha=opacity, #color='r',
                label='Trained with ours')


#设置柱体上显示数据值

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, height,'%.1f'%float(height), ha='center', va='bottom')
    #‘%.2f%float(height)这个设置是让显示的数值精度为小数点后两位小数

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

ax.set_ylabel('Test Accuracy')
#ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width)
ax.set_xticklabels(('PointNet', 'PointNet++', 'DGCNN'))
plt.ylim(88,95.5) #设置y轴的标尺
#plt.xlim(-0.5,3) #设置x轴的标尺
ax.legend()

fig.tight_layout()
plt.show()
#fig.savefig('Test Accuracy.png',dpi=600) #保存图片并设置分辨率

运行结果

对于color项,我选择使用python默认的配色
在这里插入图片描述

例二,添加误差项

在matplotlib中,errorbar方法用于绘制带误差线的统计图,基本用法如下

yerr
参数用于指定y轴水平的误差,同时该方法也支持x轴水平的误差,对应参数xerr。表现在图上是:每根柱子顶端在纵轴方向的线段。如果指定一个固定值,所有柱子的线段将一直长;如果指定一个带有不同长度值的列表,那么柱子顶部的线段将呈现不同长度。

capsize
这个参数很有趣, 对xerr或者yerr的补充说明。一般为其设置一个整数,例如 10。如果你已经设置了
yerr 参数,那么设置 capsize 参数,会在每跟柱子顶部线段上面的首尾部分增加两条垂直原来线段的线段。对 xerr 参数也是同样道理。

ecolor
参数指定error bar的颜色,可以和折线的颜色加以区分。

error_kw
设置 xerr 和 yerr 参数显示线段的参数,它是个字典类型。如果你在该参数中又重新定义了 ecolor 和 capsize,那么显示效果以这个为准。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple

#解决显示不出中文的问题
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体
mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题

n_groups = 3#几组数据

means_1 = (89.2,90.7,92.2)
means_2 = (90.9,92.9,93.4)
means_3 = (91.3,93.4,93.4)
std_1 = (0.5, 0.5, 0.5)
fig, ax = plt.subplots()#这个设置用于后面在每个主题上显示数值
#设置索引和柱体宽度
index = np.arange(n_groups)
bar_width = 0.25

opacity = 0.4#不透明度
error_config = {
    
    'ecolor': '0.3'}#error bar的颜色

rects1 = ax.bar(index, means_1, bar_width,
                alpha=opacity, #color='b',
                yerr=std_1, error_kw=error_config,
                label='Trained with A')

rects2 = ax.bar(index + bar_width, means_2, bar_width,
                alpha=opacity, #color='g',
                yerr=std_1, error_kw=error_config,
                label='Trained with B')

rects3 = ax.bar(index + bar_width + bar_width, means_3, bar_width,
                alpha=opacity, #color='r',
                yerr=std_1, error_kw=error_config,
                label='Trained with ours')


#设置柱体上显示数据值

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, height,'%.1f'%float(height), ha='center', va='bottom')
    #‘%.2f%float(height)这个设置是让显示的数值精度为小数点后两位小数

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

ax.set_ylabel('Test Accuracy')
#ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width)
ax.set_xticklabels(('PointNet', 'PointNet++', 'DGCNN'))
plt.ylim(88,95.5) #设置y轴的标尺
#plt.xlim(-0.5,3) #设置x轴的标尺
ax.legend()

fig.tight_layout()
plt.show()
#fig.savefig('Test Accuracy.png',dpi=600) #保存图片并设置分辨率

运行结果

注意:err must be [ scalar | N, Nx1 or 2xN array-like ]
yerr包含的数字个数,等于数据组数
在这里插入图片描述

扫描二维码关注公众号,回复: 14778246 查看本文章

如果您觉得有帮助请点个赞!

猜你喜欢

转载自blog.csdn.net/weixin_42785537/article/details/114288704