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'}

最新文章

  1. [转]Excel导入异常Cannot get a text value from a numeric cell解决
  2. FPGA书籍
  3. Node.js爬虫数据抓取乱码问题总结
  4. IE6下position解决父元素被撑开的问题
  5. 【JSP动态网站】JDBC连接SqlServer 2008数据库
  6. JAVA GUI学习 - JTable表格组件学习_A ***
  7. createElement、createTextNode、setAttribute使用方法
  8. 为什么做Web开发要选择PHP
  9. 第四章 go语言 数组、切片和映射
  10. worknote
  11. 最全面的Redis命令行查阅手册(收藏查看)
  12. 基于DPDK的高效包处理系统
  13. PHP——敏感词过滤
  14. 苹果电脑利用wget总是会出现无法建立 SSL 连接的问题
  15. python的类和对象
  16. win7下配置IIS
  17. 彻底搞清楚python字符编码
  18. 前端使用html2canvas截图,在canvas上绘制图片及保存图片
  19. IIS请求筛选模块被配置为拒绝包含双重转义序列的请求404.11
  20. 【mybatis】idea中 mybatis的mapper类去找对应的mapper.xml中的方法,使用插件mybatis-plugin

热门文章

  1. [20190306]共享服务模式与SDU.txt
  2. List泛型与DataTable相互转换
  3. [C#]List的Sort()、Find()、FindAll()、Exist()的使用方法举例
  4. 基数排序python实现
  5. [Hive_6] Hive 的内置函数应用
  6. Python3 实现简易局域网视频聊天工具
  7. nginx: worker process is shutting down
  8. elementUI el-input focus
  9. MySQL高级知识(十三)——表锁
  10. 为什么一定要学习linux系统?