matplotlib绘图库

Python库记录系列.

安装

pip install matplotlib
# 会自动安装依赖numpy

基本使用

常用格式

plt.plot(range(10), linestyle='--', marker='o', color='b')
# 等价于
plt.plot(range(10), '--bo')

基本概念

  • Label/标签:标明指定数据类型或分组
  • Annotation/标注:对数据的补充说明信息
  • Legend/图例:数据列表的分类说明(以颜色等区分)
import matplotlib.pyplot as plt
import numpy as np
# 
plt.ylabel("Values")

# 
plt.annotate(xy=[1,1], s="First Entry")
plt.annotate(label, # this is the text
                 (x,y), # this is the point to label
                 textcoords="offset points", # how to position the text
                 xytext=(0,10), # distance from text to points (x,y)
                 ha='center') # horizontal alignment can be left, right or center
# Legend
plt.legend(['First', 'Second'], loc=4)
t2 = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
# 注意,的使用,l1是个Line2D实例
l1, = ax.plot(t2, np.exp(-t2))
ax.legend((l1), ('exp'), loc='upper right', shadow=True)

# 添加文本/text
# 默认左对齐
plt.text(8,3,'This text ends at point (8,3)',horizontalalignment='right')

常用功能

支持中文标签

import matplotlib.pyplot as plt

# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']  
# 用来正常显示负号
plt.rcParams['axes.unicode_minus'] = False  

numpy

import numpy as np

# 范围取值
np.arange(20, 120, 20)

# 读取csv文件
data = np.genfromtxt('result.csv', delimiter=',', skip_header=True)

# 交换二维数组
data1 = np.swapaxes(data, 0, 1)

# 交换方式二
x = np.arange(4).reshape((2,2))
# 转换/对调
np.transpose(x)

扩展阅读

numpy