首页 > 其他 > 详细

matplotlib 入门之Pyplot tutorial

时间:2019-05-03 11:42:20      阅读:157      评论:0      收藏:0      [点我收藏+]

matplotlib教程学习笔记

pyplot 介绍

import matplotlib.pyplot as plt
import numpy as np
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

技术分享图片

  • 注意:pyplot的函数往往也是对象的函数
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 2, 3, 4])
ax2.plot([2, 3, 4, 5])
#ax1.ylabel("...") 没有这个方法。。。
#fig.show()会显示non-GUI-backend而不能执行, 而ax1.show() 或者ax2.show(),没有该方法
#估计得通篇看完再能窥其门径了

技术分享图片

从上面的例子可以看出,纵坐标是我们给的数据,而横坐标,pyplot会自动从0给予编号。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

技术分享图片

修饰你的图案

pyplot格式继承自matlab(我不知道)。plot的第三个可选参数是一个格式字符串,代表颜色和曲线的种类,默认为"b-"。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') #'ro' : red circles 红色的圆
plt.axis([0, 6, 0, 20]) # [xmin, xmax, ymin, ymax]
plt.show()

技术分享图片

格式字符串 [color][marker][line]

fmt = ‘[color][marker][line]‘

Colors

技术分享图片

当格式字符串只限制颜色的时候,你可以写颜色的全称,也可以用16进制来表达。
或者任意的matplotlib.colors

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], '#FF0000')
plt.axis([0, 6, 0, 20])
plt.show()

技术分享图片

Markers

技术分享图片

Line Styles

技术分享图片

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'g*--') #绿色 * 虚线
plt.axis([0, 6, 0, 20])
plt.show()

技术分享图片

利用关键字作图(大概是数据映射到属性吧)

data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

技术分享图片

传入类别

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(1, figsize=(9, 3)) #figsize: 长9个单位,高3个单位

plt.subplot(131)  #131 
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

技术分享图片

控制线的属性

线有许多属性,比如线的宽度,虚线的形式等等。

我们有很多方法来设置线的属性:

plt.plot(x, y, linewidth=2.0)

使用line2D对象的setter方法也可以完成。

x1 = np.array([1, 2, 3, 4])
y1 = x1 ** 2
x2 = np.array([4, 3, 2, 1])
y2 = np.sin(x2)
line1, line2 = plt.plot(x1, y1, x2, y2)
line1.set_antialiased(False) #关闭抗锯齿
line2.set_linewidth(5.0)
plt.show()

技术分享图片

使用setp()指令同样能够办到,这玩意儿还会返回图片的各种属性。

x1 = np.array([1, 2, 3, 4])
y1 = x1 ** 2
x2 = np.array([4, 3, 2, 1])
y2 = np.sin(x2)
lines = plt.plot(x1, y1, x2, y2)
plt.setp(lines, color='r', linewidth=2.0)

技术分享图片

Line2D的属性

技术分享图片

pro1 = {
       'alpha':0.2,
       'animated':True, #动画?啥效果?
       'antialiased':True,#抗锯齿 默认为True
       'color': 'red',
       'dash_capstyle': 'butt', #不知道干啥的  包裹起来?
       'dash_joinstyle': 'miter', #不知道干啥的
       'label': "会出现吗?",
       'linestyle': 'steps',
       #'lod': True 为啥没这属性
       'marker': '+',
       'markeredgecolor': 'red', #断点的颜色?
       'markeredgewidth': 2.0, #断点的大小
       'markerfacecolor': 'yellow',
       'markersize': 6.0 #这个是那个断点的大小,可是是什么压制了它的洪荒之力
       
       }
pro2 = {
        'alpha':0.8,
        'animated':False,
        'aa':False,
        'c': '#00FF00',
        'linestyle': '--',
        'marker': '1',
        'mec': 'blue',
        'mew': 3.0,
        'mfc': 'yellow', #啥意思啊,嵌了一层黄色
        'ms': 2.0
    
        }
x1 = np.arange(20)
y1 = x1
x2 = np.linspace(0, 20, 50)
y2 = np.sin(x2)
line1, line2 = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(line1, **pro1)
plt.setp(line2, **pro2)
plt.show()

技术分享图片

操作多figures和axes

matlab和pyplot都有当前figure,axes的概念,所有画图操作都会应用到当前的axes上。函数gca()会返回当前的axes对象,而gcf()会返回当前figure对象。

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)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

技术分享图片

subplot(mnk)

m: numrows
n: numcols
k: plot_numer [1-m*n]

就相当于把一块画布割成m行n列,即有mn块小区域,k就是我们要子图所放的区域的标识,从1到mn。而且,从下面的例子中可以看出,位置是从上到下,从左往右标号的。

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

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

plt.figure(1)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(222)
plt.plot(t1, f(t1), 'ro', t2, f(t2), 'k')

plt.subplot(223)
plt.plot(t1, f(t1), 'go', t2, f(t2), 'k')
plt.subplot(224)

plt.plot(t1, f(t1), 'yo', t2, f(t2), 'k')
plt.show()

技术分享图片

clf()清空当前figure, cla()清空当前axes.

另外,figure所占内存,只用当调用close()的时候才会完全释放。

加入Text

text() :可将文本加入至任意位置
xlabel(), ylabel(), title() :加入至固定位置

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

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


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
#r表示原始字符串,否则得这么写plt.text(60, .025, '$\\mu=100,\ \\sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

技术分享图片

Annotating text

annoate()


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),
             )

plt.ylim(-2, 2)
plt.show()

技术分享图片

非线性axes

pyplot提供非线性标度,如对数化等等。(纵坐标好像还是原来的y,只是图像变了)

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)


# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

技术分享图片

matplotlib 入门之Pyplot tutorial

原文:https://www.cnblogs.com/MTandHJ/p/10804598.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!