matplotlib 语言基础

1. matplotlib创建画布并添加内容

# -*- coding: utf-8 -*-
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 09:43:31 2020

@author: 12965
"""

import numpy as np
import matplotlib.pyplot as plt


x = np.arange(1,2.1,0.001);

'''
    x,y刻度最大值限制
'''
plt.xlim((0,2));
plt.ylim((0,2));
'''
    自定义x,y刻度
'''
plt.xticks([0,0.2,0.4,0.6]);
plt.yticks([0,0.3,0.6,0.9]);

plt.plot(x,x**3);
plt.plot(x,x**8);
plt.plot(x,x**10);
plt.show();


2. 创建多个画布并添加标题和X Y坐标label

# -*- coding: utf-8 -*-

'''
    创建多个画布并添加标题和X Y坐标label
'''
import numpy as np
import matplotlib.pyplot as plt



x = np.arange(0,2.1,0.01);
plt.title("LIN1");
plt.xlabel('X');
plt.ylabel('Y');
plt.plot(x,x**3);
plt.figure();## 创建一个新的画布

plt.title("LIN2");
plt.xlabel('X2');
plt.ylabel('Y2');
plt.plot(x,x**10);

plt.legend(['y = x^3','y = x^10']); # 显示各个颜色的线代表的函数
plt.show();

3. 保存matplotlib生成图形作为图片保存到本地

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,1,0.01);
plt.plot(x,x**3);
plt.xlabel('X');
plt.ylabel('Y');
plt.title('OK')
plt.legend(['y = x^3']);
plt.savefig("C:/Users/12965/Desktop/a.png");# 注意斜杠的写法
plt.show();

4. 在同一张图中绘制子图

import numpy as np
import matplotlib.pyplot as plt


p1 = plt.figure(figsize=(10,8));# 设置图形大小
ax1 = p1.add_subplot(2,1,1);# 绘制第一张子图


x = np.arange(0,np.pi*2,0.001);
plt.plot(x,np.sin(x));
plt.legend(['sin']);


ax2 = p1.add_subplot(2,1,2);# 绘制第二幅子图
plt.plot(x,np.cos(x));
plt.legend(['cos']);

plt.show();

5. 二维散点图

import numpy as np
import matplotlib.pyplot as plt
import random
 
xarr = np.zeros(100, dtype = np.int);
yarr = np.zeros(100, dtype = np.int);
i = 0;
while i<100:
    xarr[i] = random.randint(0,100);
    yarr[i] = random.randint(0,100);
    print('^_^',xarr[i]);
    i = i+1;
    
plt.rcParams['font.sans-serif'] = 'SimHei' ## 使用rc参数设置:中文显示
plt.rcParams['axes.unicode_minus'] = False


plt.figure(figsize=(10,8)) ## 设置画布大小
x = np.arange(0,100,10);

plt.scatter(xarr,yarr, marker='*',c='red')## 绘制二维数据散点图

plt.grid()
plt.xlabel('年份')
plt.ylabel('生产总值(亿元)')



plt.show()

散点图效果展示:

6. 3D动画图

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation

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


def Gen_RandLine(length, dims=2):
    """
    Create a line using a random walk algorithm

    length is the number of points for the line.
    dims is the number of dimensions the line has.
    """
    lineData = np.empty((dims, length))
    lineData[:, 0] = np.random.rand(dims)
    for index in range(1, length):
        # scaling the random numbers by 0.1 so
        # movement is small compared to position.
        # subtraction by 0.5 is to change the range to [-0.5, 0.5]
        # to allow a line to move backwards.
        step = ((np.random.rand(dims) - 0.5) * 0.1)
        lineData[:, index] = lineData[:, index - 1] + step

    return lineData


def update_lines(num, dataLines, lines):
    for line, data in zip(lines, dataLines):
        # NOTE: there is no .set_data() for 3 dim data...
        line.set_data(data[0:2, :num])
        line.set_3d_properties(data[2, :num])
    return lines

# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Fifty lines of random 3-D lines
data = [Gen_RandLine(25, 3) for index in range(50)]

# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]

# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')

ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
                                   interval=50, blit=False)

plt.show()

7. 3D动画–sin函数

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))


def init():  # only required for blitting to give a clean slate.
    line.set_ydata([np.nan] * len(x))
    return line,

'''
	对i的解释:
		这里的i表示的是帧数,是一个一直变化的递增量。
	为什么要加上 + i / 100:
		如果不加上则为:line.set_ydata(np.sin(x))
		那么会是什么效果?就会显示一个静态的单个周期sin正弦图
		因为x只是一个0~2PI之间的数组数据,所以y = np.sin(x)
		这样的y值只有一个周期之内的数据,所以需要让x一直递增,
		我们才可以看到连续的周期性变化的正弦图,其实说白了,就
		是让角度x一直递增。
'''
def animate(i):
    line.set_ydata(np.sin(x + i / 100))  # update the data.
    return line,


ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=2, blit=True, save_count=50)

# To save the animation, use e.g.
#
# ani.save("movie.mp4")
#
# or
#
# from matplotlib.animation import FFMpegWriter
# writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# ani.save("movie.mp4", writer=writer)

plt.show()

效果图展示:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值