python matplotlib入门(二) Matplotlib 作图生命周期

  上篇 python matplotlib入门(一)主要介绍了matplotlib的workflow, 这一篇将主要介绍 matplotlib 绘图的生命周期,只有了解了matplotlib 的内部工作方式,后面具体的操作才能够得心应手。为了方便阐述,我们将从一些原始数据开始,最后保存一个自定义可视化图形。在此过程中,我们将尝试使用Matplotlib突出一些简洁的功能和最佳实践。

  整个生命周期包括: 数据准备、绘图、调整样式、自定义图像、数据格式化、图像叠加、保存图像等。整个过程,本质是基于matplotlib backend所提供的一张canvas上建立一个Figure对象,然后在Figure对象上添加一或多个Axes,最后就是在Axes对象上绘制图形。

   数据

# 公司销售数据
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

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)

  开始作图

  在这里,我们使用python matplotlib入门(一)中提到的面向对象的方法来作图,我们首先生成一个figure.Figure和axes.Axes的实例。所谓Figure就像一个画布,Axes是画布的一部分,我们将在其上进行特定的可视化。

fig, ax = plt.subplots()  # 生成 图 和 坐标轴对象
# 在坐标轴上进行绘图
ax.barh(group_names, group_data)

这里写图片描述

   控制样式

不难发现,上图长的有点着急, 坐标轴显示有严重问题,所以我们需要通过调整样式,来给它修正一下。

plt.style.use('fivethirtyeight')
# 内置支持的样式有:
"""
['seaborn-ticks', 'ggplot', 'dark_background', 'bmh', 'seaborn-poster', 'seaborn-notebook', 'fast', 'seaborn', 'classic', 'Solarize_Light2', 'seaborn-dark', 'seaborn-pastel', 'seaborn-muted', '_classic_test', 'seaborn-paper', 'seaborn-colorblind', 'seaborn-bright', 'seaborn-talk', 'seaborn-dark-palette', 'tableau-colorblind10', 'seaborn-darkgrid', 'seaborn-whitegrid', 'fivethirtyeight', 'grayscale', 'seaborn-white', 'seaborn-deep']
"""

  自定义图形

下面我们来调整一下这个图:

# 修改rcParams参数,使图像自动排版(效果有限)
# 关于 rcParams 在下一篇博客介绍
plt.rcParams.update({'figure.autolayout': True})

fig, ax = plt.subplots(figsize=(8, 4))  # figsize= (width, height) 调整图像长宽比
ax.barh(group_names, group_data)

# 对横坐标进行旋转以及水平右对齐
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

# 设置图形的 xlabel, ylabel, x轴刻度范围, 图像标题
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
       title='Company Revenue')

这里写图片描述

这样图像基本就还看的过去了,不会像之前那么难看了,是不是?

  数据格式控制

​ 对于标签,我们可以使用ticker.FuncFormatter类以函数的形式指定自定义格式。下面我们将定义一个以整数作为输入的函数,并返回一个字符串作为输出。

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

formatter = FuncFormatter(currency)

然后我们可以将此格式化程序应用于我们的图上的标签。为此,我们将使用轴的xaxis属性。这样就可以在我们的绘图上对特定轴执行操作。

# 将格式化函数 赋给 xaxis
ax.xaxis.set_major_formatter(formatter)

这里写图片描述

   Overlap 整合

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

# Overlap 添加一条垂直线
ax.axvline(group_mean, ls='--', color='r')

# 标记公司
for group in [3, 5, 8]:
    ax.text(145000, group, "New Company", fontsize=10,
            verticalalignment="center")

# Now we'll move our title up since it's getting a little cramped
ax.title.set(y=1.05)

ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
       title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])
fig.subplots_adjust(right=.1)

plt.show()

这里写图片描述

  保存图像

# 保存图像
fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")
# 支持的图像格式有:
"""
{'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'}
"""

猜你喜欢

转载自blog.csdn.net/jeffery0207/article/details/81270000