matplotlib教程学习笔记

这篇教程旨在展示如何开始、完善、结束可视化过程。我们将以一些原始的数据为开端,以保存可视化的图片为结尾。在其过程中,我们会展示一些整洁的特性和实用的练习。

Note

  • figure对象是图片的最终体,可能包含1个或多个Axes对象
  • Axes对象代表独立的plot,请不要把它和axis(坐标轴)混淆

数据


# sphinx_gallery_thumbnail_number = 10
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)

准备开始

第一步,我们先创建一个figure对象和axes对象,subplots可以替我们完成这项工作。

fig, ax = plt.subplots()

第二步,现在我们已经有了一个Axes实例,可以开始着手在上面“作画”了。

ax.barh(group_names, group_data) #水平柱状图

操控风格

matplotlib拥有许多的绘图风格,我们可以通过plt.style来查看。

print(plt.style.available)
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
style = plt.style.available
n = len(style)

fig, axs = plt.subplots( n // 4 + 1, 4, figsize=(10, 20), sharex='all', sharey='all')# n//4+1 * 4 个axes
#figsize=(width,height)!!! 像素大小为width*10 * height*10
count = 0
try:
    for i in range( n // 4 +1):
        for j in range(4):
            count += 1
            if count == n:
                raise ValueError
            plt.style.use(style[count])
            axs[i, j].barh(group_names, group_data)
            axs[i, j].set_title(style[count])

except ValueError: pass

plt.show()

风格控制背景色,线宽等许多特性(虽然我从上图没看出什么来)。

我错了!!!

经过实验,发现plt.style.use语句必须在fig对象创建前,而且这个style好像只能统管整个fig,所以我试图一个fig不同Axes不同style的计划就这么失败了。不知道有什么办法能够解救一下。

定制图像

我已经拥有了比较普通的图像, 我们可以为其添加一些微妙的有趣的变化。比方说,让x轴的标签旋转。

首先,我们要获得x轴上的标签

fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()

使用pyplot.setp()函数可以便捷地调整属性

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

使用

plt.rcParams.update({'figure.autolayout': True})

命令matplotlib来自动排版,使得字体不要超出(可能由于后端的问题,测试图片并没有出现这种情况。)

接下来,我们使用axes.Axes.set()来为Axes添加标题等属性,当然,这项工作也可以由setp()来完成。


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')
#plt.setp(ax, xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue')

特别注意!!! figsize=(width, height)!!!

特别注意,figsize属性是widthheight, 与像素的关系是(width10) * (height*10),是10倍关系。

fig, ax = plt.subplots(figsize=(8, 4))
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')

格式化标签

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)  #通过FuncFormatter可以定制标签
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.xaxis.set_major_formatter(formatter)

组合多个可视化对象?

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)

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

# Add a vertical line, here we set the style in the function call
ax.axvline(group_mean, ls='--', color='r')

# Annotate new companies
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(left=0.3, right=0.8)  #感觉改了啊,跟例子的不一样了 left,right后面的地方估计直接都是从左往右计了吧

plt.show()

[图片上传中…(image.png-5931a1-1552124449964-0)]

保存你的图片

# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")

#transparent = True, 背景色设置为透明,如果支持的话

#dpi: 控制解析度(dots per square inch)

#bbox_inches=“tight” fits the bounds of the figure to our plot.

支持哪些格式呢

print(fig.canvas.get_supported_filetypes())
{'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'}

matplotlib 入门之The Lifecycle of a plot的更多相关文章

  1. 绘图神器-matplotlib入门

    这次,让我们使用一个非常有名且十分有趣的玩意儿来完成今天的任务,它就是jupyter. 一.安装jupyter matplotlib入门之前,先安装好jupyter.这里只提供最为方便快捷的安装方式: ...

  2. Python 绘图库Matplotlib入门教程

    0 简单介绍 Matplotlib是一个Python语言的2D绘图库,它支持各种平台,并且功能强大,能够轻易绘制出各种专业的图像. 1 安装 pip install matplotlib 2 入门代码 ...

  3. Matplotlib 入门

    章节 Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Mat ...

  4. IPython绘图和可视化---matplotlib 入门

    最近总是需要用matplotlib绘制一些图,由于是新手,所以总是需要去翻书来找怎么用,即使刚用过的,也总是忘.所以,想写一个入门的教程,一方面帮助我自己熟悉这些函数,另一方面有比我还小白的新手可以借 ...

  5. matplotlib入门--1(条形图, 直方图, 盒须图, 饼图)

    作图首先要进行数据的输入,matplotlib包只提供作图相关功能,本身并没有数据读入.输出函数,针对各种试验或统计文本数据输入可以使用numpy提供的数据输入函数. # -*- coding: gb ...

  6. 【Matplotlib-01】Python 绘图库 Matplotlib 入门教程

    环境: Windows10 python3.6.4 numpy1.14.1 matplotlib2.1.2 工具:Cmder 目录: 1.线性图 2.散点图 3.饼状图 4.条形图 5.直方图 例1: ...

  7. matplotlib 入门之Sample plots in Matplotlib

    文章目录 Line Plot One figure, a set of subplots Image 展示图片 展示二元正态分布 A sample image Interpolating images ...

  8. matplotlib 入门之Pyplot tutorial

    文章目录 pyplot 介绍 修饰你的图案 格式字符串 [color][marker][line] Colors Markers Line Styles 利用关键字作图(大概是数据映射到属性吧) 传入 ...

  9. matplotlib 入门之Usage Guide

    文章目录 Usage Guide plotting函数的输入 matplotlib, pyplot, pylab, 三者的联系 Coding style Backends 后端 matplotlib教 ...

随机推荐

  1. Alwayson查询主副本不同的JOB,Linkserver,Login

    DECLARE @SQL AS VARCHAR(5000), @Primary AS VARCHAR(50), @Secondy AS VARCHAR(50); SELECT @Primary='AA ...

  2. VMware虚拟机安装CentOS7【转】-添加部分注释(自己看着方便)

    本文稍作改动,添加部分说明,原文链接:https://www.cnblogs.com/wcwen1990/p/7630545.html 本文基于vmware workstations进行CentOS7 ...

  3. IPerf——网络测试工具介绍与源码解析(5)

    本篇随笔讲述一下TCP协议下,双向测试模式和交易测试模式下客户端和服务端执行的情况: 双向测试模式: 官方文档的解释 Run Iperf in dual testing mode. This will ...

  4. Java循环语句怎么用?经典排序算法见真知

    Java中循环语句的使用,莫过于在排序算法中使用得最为经典. 排序算法非常的多,不过大体可以分为两种: 一种是比较排序,主要有:冒泡排序,选择排序,插入排序,归并排序,堆排序,快速排序等. 另一种是非 ...

  5. xshell远程登录工具的星号密码查看方法

    当我们在使用ftp,或者xshell等远程登录工具的时候,连接的密码是用星号*处理的,无法查看到,该如何查看到原始的密码呢? 推荐一款星号密码查看器,可以查看一些软件的带星号的密码,非常好用. 下载地 ...

  6. ​June 10. 2018, Week 24th, Sunday

    There is no friend as loyal as a book. 好书如挚友,情谊永不渝. From Ernest Miller Hemingway. Books are my frien ...

  7. CISCO 动态路由(RIP)

    RIP(路由信息协议):是一种内部网关协议(IGP),是一种动态路由选择协议,基于距离矢量算法(DistanceVectorAlgorithms),使用“跳数”(即metric)来衡量到达目标地址的路 ...

  8. 注册mySQL到JDBC驱动程序方法浅谈

    一.注册方法(4种) 1)服务提供者框架: 符合JDBC 4.0规范的驱动程序包含了一个文件META-INF/services/java.sql.Driver,在这个文件中提供了JDBC驱动实现的类名 ...

  9. 【Teradata】移动空间语句

    1.移动10G空间从sysdba到dbc create database td_tmp_db from sysdba as perm=10E9; give td_tmp_db to "dbc ...

  10. HIVE配置错误信息

    原因:版本问题 解决方法:cp /root/hive/lib/当前的jlinexx.jar /root/hadoop/share/hadoop/yarn/lib