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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值