Python常用模块机器学习与数据挖掘Python 运维

Python 绘图,我只用 Matplotlib(三)—— 柱状

2017-11-26  本文已影响1582人  猴哥爱读书
图片来自 unsplash

上篇文章,我已经讲解绘制图像大致步骤,接下来的系列文章将分别对各种图形做讲解。其实就是了解各个图种的绘图 API。文章就讲解第一种图形,柱状图。

1 基础

绘制柱状图,我们主要用到bar()函数。只要将该函数理解透彻,我们就能绘制各种类型的柱状图。

我们先看下bar()的构造函数:bar(x,height, width,*,align='center',**kwargs)

其他可选参数有:

下面我就调用 bar 函数绘制一个最简单的柱形图。

import matplotlib.pyplot as plt
import numpy as np

# 创建一个点数为 8 x 6 的窗口, 并设置分辨率为 80像素/每英寸
plt.figure(figsize=(8, 6), dpi=80)

# 再创建一个规格为 1 x 1 的子图
plt.subplot(1, 1, 1)

# 柱子总数
N = 6
# 包含每个柱子对应值的序列
values = (25, 32, 34, 20, 41, 50)

# 包含每个柱子下标的序列
index = np.arange(N)

# 柱子的宽度
width = 0.35

# 绘制柱状图, 每根柱子的颜色为紫罗兰色
p2 = plt.bar(index, values, width, label="rainfall", color="#87CEFA")

# 设置横轴标签
plt.xlabel('Months')
# 设置纵轴标签
plt.ylabel('rainfall (mm)')

# 添加标题
plt.title('Monthly average rainfall')

# 添加纵横轴的刻度
plt.xticks(index, ('Jan', 'Fub', 'Mar', 'Apr', 'May', 'Jun'))
plt.yticks(np.arange(0, 81, 10))

# 添加图例
plt.legend(loc="upper right")

plt.show()

运行结果为:


点击查看大图

2 进阶

bar 函数的参数很多,你可以使用这些参数绘制你所需要柱形图的样式。如果你还不会灵活使用这样参数,那就让我们来学习 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()

运行结果如下:


点击查看大图

开动你的大脑,想想还能绘制出什么样式的柱形图。


上篇阅读:彻底理解Iterable、Iterator、generator
推荐阅读:Python 绘图,我只用 Matplotlib(二)


上一篇 下一篇

猜你喜欢

热点阅读