Python matplotlib绘图学习笔记

测试环境:

Jupyter QtConsole 4.2.1
Python 3.6.1

1.  基本画线:

以下得出红蓝绿三色的点

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

以下设置线宽,得到比较粗一点儿的线,如果 plot中只给了一维信息,

默认图形是把数值匹配成纵坐标的

x = np.arange(0., 5., 0.1)
plt.plot(x, 4*x, linewidth=8.0)
plt.show()

以下得到同一个图中两幅分图:

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)
plt.subplot(211)#表示两幅图竖着排列
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)#如果为(221)和(222)表示横排列
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

2. 画直方图

以下为正态分布

np.random.seed(19680801)

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.1)


plt.xlabel('Smarts')
plt.ylabel('Probability')
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()

其中

n, bins, patches = plt.hist(arr, bins=10, normed=0, facecolor='black', edgecolor='black',alpha=1,histtype='bar')

hist的参数非常多,但常用的就这六个,只有第一个是必须的,后面四个可选

arr: 需要计算直方图的一维数组

bins: 直方图的柱数,可选项,默认为10

normed: 是否将得到的直方图向量归一化。默认为0

facecolor: 直方图颜色

edgecolor: 直方图边框颜色

alpha: 透明度

histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’

返回值 :

n: 直方图向量,是否归一化由参数normed设定

bins: 返回各个bin的区间范围

patches: 返回每个bin里面包含的数据,是一个list

3. 特殊符号和标注

用以下方式可以写出特殊的数学公式符号:

plt.title(r'$sigma_i=15$')

以下代码表示文字显示区域是
(3, 1.5)指向坐标位置是(2,1)
import numpy as np
import matplotlib.pyplot as plt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )#shrink表示箭头缩放情况,值越小显示越大
plt.ylim(-2,2)#表示y坐标轴的上界和下界 plt.show()
 

 更多信息:

http://blog.csdn.net/panda1234lee/article/details/52311593

原文地址:https://www.cnblogs.com/nyc1893/p/7107218.html