Fork me on GitHub

Python matplotlib绘图

Python matplotlib

需要安装matplotlib、numpy等模块

基础语法

import matplotlib.pyplot as plt
# 设置标题
plt.title('AAPL stock price change')
#设置图例
plt.legend()
# 设置坐标轴标签
plt.xlabel('time')
plt.ylabel('stock price')
# 设置坐标轴范围:可以是日期、数值
plt.xlim(datetime(2008,1,1), datetime(2010,12,31))  
plt.ylim(0,300)
# 或  
plt.axis([datetime(2008,1,1), datetime(2010,12,31), 0, 300])
# 设置坐标轴刻度
plt.xticks()
plt.yticks()
# 设置图像大小
plt.figure(figsize=[6,6])   
# 设置(箭头)标注
plt.annotate()
# 添加文字
plt.text()
# 或
AxesSubplot.text()

基本用法

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.plot(x, y)
plt.show()

Figure

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x ** 2
# para: num, figsize
plt.figure()
plt.plot(x, y1)
plt.figure()
plt.plot(x, y2)
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()


散点图

import matplotlib.pyplot as plt
import numpy as np
n = 1024
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
# color
color = np.arctan2(y, x)
# 绘制散点
plt.scatter(x, y, s=75, c=color, alpha=0.5)
# 设置坐标轴范围
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
plt.show()

柱状图

import matplotlib.pyplot as plt
import numpy as np
n = 12
x = np.arange(n)
y1 = (1 - x/ float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x/ float(n)) * np.random.uniform(0.5, 1.0, n)
# 绘制柱状图
plt.bar(x, +y1, facecolor='#9999ff', edgecolor='white')
plt.bar(x, -y2, facecolor='#ff9999', edgecolor='white')
# 为每个柱子添加数值
for i, j in zip(x, y1):
# ha: horizontal alignment
plt.text(i, j + 0.05, '%.2f' % j, ha='center', va='bottom')
for i, j in zip(x, y2):
# ha: horizontal alignment
plt.text(i, -j - 0.05, '%.2f' % -j, ha='center', va='top')
# 设置坐标轴范围
plt.xlim((-.5, n))
plt.ylim((-1.25, 1.25))
plt.show()

多图合一

subplot

import matplotlib.pyplot as plt
plt.figure()
# 创建小图 2行2列
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 2])
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 3])
plt.subplot(2, 2, 4)
plt.plot([0, 1], [0, 4])
plt.show()

import matplotlib.pyplot as plt
plt.figure()
# 创建小图 2行
# 第1行 1列 相当于占3个位置
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# 第2行 3列,第一行占3个位置,第2行从4开始
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 2])
plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 3])
plt.subplot(2, 3, 6)
plt.plot([0, 1], [0, 4])
plt.show()

分格显示

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 1: subplot2grid
##########################
plt.figure()
# 整个figure分成3行3列
# 从位置(0,0)开始, colspan 跨3列 rowspan 跨1行
# stands for axes
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax1.plot([1, 2], [1, 2])
# 与plt类似,对应设置需要加上 set_
ax1.set_title('ax1_title')
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
ax5 = plt.subplot2grid((3, 3), (2, 1))
plt.tight_layout()
plt.show()
# method 2: gridspec
#########################
plt.figure()
# 划分为3行3列
gs = gridspec.GridSpec(3, 3)
# use index from 0
# 第1行,所有列
ax6 = plt.subplot(gs[0, :])
# 第2行,前2列
ax7 = plt.subplot(gs[1, :2])
# 后2行,第2列
ax8 = plt.subplot(gs[1:, 2])
# 第3行,第1列
ax9 = plt.subplot(gs[-1, 0])
# 第2行,第2列
ax10 = plt.subplot(gs[-1, -2])
plt.tight_layout()
plt.show()
# method 3: easy to define structure
####################################
# 划分为2行2列, 共享x轴、y轴
# ()设置每行 ax 占据的位置
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()



图中图

import matplotlib.pyplot as plt
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# 位置、宽、高取fig大小的比列
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# main axes
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
# inside axes
# 位置、宽、高取fig大小的比列
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
# different method to add axes
####################################
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()

主次坐标

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
# 反转ax1的y坐标
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()

参考资料

Matplotlib User's Guide

Matplotlib Python 画图教程 (莫烦Python)

GithubCode

posted @   ZTianming  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
欢迎阅读『Python matplotlib绘图』

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示