11matplotlib-柱状图绘制流程

在matplotlib中存在两套画图命令:

  • 基于面向对象的方式OO
  • 基于pyplot函数接口的方式

作者还是推荐我们使用object-oriented interface的方式绘制图形

以后绘图中涉及到的一些常见操作,我会用锚点标注好;以后查具体代码的时候也会非常的快

绘图数据

准备绘图数据,包含了几个人的收入信息吧;准备绘制一个柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np
import matplotlib.pyplot as plt

#数据字典
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}

group_data = list(data.values()) ##工资
group_names = list(data.keys()) ##人名
group_mean = np.mean(group_data) ## 平均值

创建实例对象

采用面向对象的接口,生成figure.Figureaxes.Axes实例对象

  • figure.Figure相当于画布的作用,在上面可以绘制多个图片
  • axes.Axes就是一副完整的图片,多个图片可以绘制在一块画布上
1
fig, ax = plt.subplots() ##生成实例对象

png

1
2
fig,ax=plt.subplots()
ax.barh(group_names,group_data) ##绘制柱状图

png

控制图片样式

这里相当于ggplot2里的theme,可以使用print(plt.style.available)查看系统自带的样式;使用plt.style.use('样式名')使用对应的样式;如下图所示,选择好样式后,就在图中添加了网格线,改变了柱子的颜色

1
2
3
plt.style.use('fivethirtyeight')
fig,ax=plt.subplots()
ax.barh(group_names,group_data)

png

旋转x轴label

当坐标轴上的label太长的时候,两个刻度之间可能会发生重叠。因此可以通过旋转label的方法调整label的显示。
首先的获取坐标轴上的label对象,使用pyplot.setp()函数设置对应的属性

1
2
3
4
fig,ax=plt.subplots()
ax.barh(group_names,group_data)
xlabels=ax.get_xticklabels() ##获取坐标轴label信息
plt.setp(xlabels,rotation=45,horizontalalignment='right') ##

png

给图片添加label

除了修改刻度线上的label,同样可以给图片的坐标轴label,图片的label,以及坐标轴显示范围。
所有的操作都是采用面向对象接口

  • xlim参数修改坐标轴显示范围
  • xlabel 修改坐标轴label
  • title 修改图片label
1
2
3
4
5
6
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')

png

批量修改坐标轴刻度label

通过定义一个函数来处理传进来的每个label,传递的函数需要使用tick对象进行实例化

报错 https://stackoverflow.com/questions/25119193/matplotlib-pyplot-axes-formatter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
## 定义处理函数
import matplotlib.ticker as tick
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s

fig, ax = plt.subplots(figsize=(6, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
#ax.get_xaxis().get_major_formatter()
ax.xaxis.set_major_formatter(tick.FuncFormatter(currency))

png

组合多个axes

直接操作ax对象,再使用对应的作图函数生成对应的图片

1
2
3
4
5
fig,ax =plt.subplots(figsize=(8,8))
ax.barh(group_names,group_data)
labels=ax.get_xticklabels()
plt.setp(labels,rotation=45,horizontalalignment='right')
ax.axvline(group_mean, ls='--',c='red') ##

png

保存图片

调用figure对象的savefig方法保存图片;在保存图片之前可以查看支持保存的图片格式

  • transparent图片背景是否透明
  • dpi 图片清晰度
  • format 保存格式
  • bbox_inches="tight" 图片与画布紧密排布
1
2
print(fig.canvas.get_supported_filetypes()) ## 查看支持保存格式
fig.savefig("test.pdf",format="pdf", bbox_inches="tight",transparent=False)
#支持的类型
{'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
------ 本文结束 thankyou 感谢阅读 ------

欢迎扫一扫上面的微信二维码,订阅 codeHub 公众号