matplotlib 常用命令汇总

matplotlib 是python的一个画图工具包(主要针对2D图形),其使用与matlab类似。

在使用matplotlib 之前先要安装,同时 matplotlib 又依赖于 numpy。 简单起见,可以直接安装anaconda,这是一个python数据处理和分析的工具包,已经包含了 numpy 和 matplotlib。

  • 提供横坐标和纵坐标点画图,画简单的图
import matplotlib.pyplot as plt

plt.plot([1,2,3,4]) # [1, 2, 3, 4] 为Y轴,X周默认从0开始
plt.ylabel('some numbers') # 修改Y周名称 plt.show()

plt.plot([1,2,3,4], [1, 2, 3, 4]) # 同时提供X坐标和Y坐标

plt.plot([1,2,3,4], [1,4,9,16], 'ro') # 'ro' 设置格式,'r'代表 red, 'o' 代表远点;
plt.axis([0, 6, 0, 20]) # 设置X轴和Y轴的最大值

 

  • 一张图上面画多条曲线
import numpy as np

t = np.arange(0., 5., 0.2)
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')  # 将y=x, y=x2, y=x3 画在同一幅图中
  • 设置线的属性

线的属性包括宽度(linewidth)、点类型(dashes),其他属性见这里

用法示例:

plt.plot(x, y, linewidth=2.0)  # 设置线的宽度

line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialising

通过 setp 方法设置属性

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
  • 多图和多坐标模式
import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)   # 当前图片编号,确实使用 figure(1),所以只有一张图片的时候,可以不写
plt.subplot(211)   # 三个数字分别为行数、列数、坐标系编号,坐标系编号 < 行数 * 列数
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

 一个完整的例子

import matplotlib.pyplot as plt
plt.figure(
1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1,2,3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4,5,6]) plt.figure(2) # a second figure plt.plot([4,5,6]) # creates a subplot(111) by default plt.figure(1) # figure 1 current; subplot(212) still current plt.subplot(211) # make subplot(211) in figure1 current plt.title('Easy as 1,2,3') # subplot 211 title
  • 为图添加文本
import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')  #  设置X轴名称
plt.ylabel('Probability')   # 设置Y轴名称
plt.title('Histogram of IQ')   #设置图片标题
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')   #添加文本
plt.axis([40, 160, 0, 0.03])   # 设置坐标范围
plt.grid(True)    #  添加网格参照线
plt.show()

转载于:https://www.cnblogs.com/cbffr/p/4721530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值