matplotlib

matplotlib

import numpy as np
import matplotlib.pyplot as mp

# 生成基本操作
"""
x = np.arange(1, 8)
y = np.random.randint(1, 100, size=7)  # 随机生成一维数组,如果是二维,改变size为[2,6]
mp.plot(x, y)  # 生成图像参数
"""
# 生成函数
# x = np.linspace(-np.pi, np.pi, 1000)
# sinx = np.sin(x)
# cosx = np.cos(x)
# mp.plot(x * 100, sinx * 100, linestyle=':')
# mp.plot(x * 100, cosx * 100, label=r'$y=sin(x)$')
# 生成水平和垂直线
"""
mp.vlines([10, 20, 30, 40], [20, 30, 30, 40], [30, 40, 30, 40], colors='red')  # 垂直线
mp.hlines(y=45, xmin=10, xmax=90, colors='red')  # 水平线
"""

"""
线下拆分1000个点并且生成正余弦图
"""

# 划线基础属性
"""
linestyle='' 类型有 - -- -. :
linewidth=1
color='red'
alpha=0.5
"""
# 设置坐标范围 其实也可以理解为可视区间
"""
mp.xlim(0, np.pi)
mp.ylim(0, 100)
"""
# 设置刻度
"""
mp.xticks(val_list,text_list)
mp.yticks(val_list,text_list)
eg:
使用LaTex 排版语法
mp.xticks([0, 50, 80, 100], [r'$a = x^2 - y^3 \tag{1}\label{1}$', 'd1'])
"""
# 设置坐标轴
"""
上下左右四个轴
ax = mp.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
"""
# 设置图例
"""
mp.legend(loc="")
loc可以不指定
"""
# 设置特殊点
"""
mp.scatter([1], [2],
           marker='s',  # 点的类型
           s=22,  # 大小
           edgecolor='red',  # 边缘色
           facecolor='blue',  # 填充色
           zorder=3  # 编号越大,图层赵靠上
           )

"""
# 设置备注点
"""
mp.annotate(
    r'aaa',  # 显示的文本
    xycoords='data',  # 使用什么坐标系
    xy=(10, 20),  # 备注点的坐标
    textcoords='offset points',  # 备注文本使用的坐标系
    xytext=(30, 40),  # 备注文本的坐标
    fontsize=15,  # 备注文本字体
    arrowprops=dict(
        arrowstyle='->',
        connectionstyle='angle3'
    )  # 目标点的箭头样式,可以不写样式
)
"""
# 绘制新窗口
"""
mp.figure(
    'A',  # 窗口标题
    # figsize=(4, 3),  # 窗口大小
    dpi=120,  # 像素密度
    facecolor='gray'  # 背景色
)
mp.title("BBBBBBBB")  # 图表标题
mp.xlabel("XXXXX1234", fontsize=12)  # 水平轴文本
mp.ylabel("YYYYY1234", fontsize=12)  # 垂直轴文本
mp.tick_params(labelsize=8)  # 刻度参数
mp.grid(linestyle='-.')  # 风格线
mp.tight_layout()  # 紧凑布局
mp.plot(x * 100, sinx * 100, linestyle=':')

"""
# 绘制子图
"""
fig, a = mp.subplots(2, 2, sharex='col', sharey='row')

x = np.arange(1, 5)

# 绘制平方函数
a[0][0].plot(x, x * x)
a[0][0].set_title('square')
# a[0][1].set_xticks([])
# a[0][1].set_yticks([])

# 绘制平方根图像
a[0][1].plot(x, np.sqrt(x))
a[0][1].set_title('square root')

# 绘制指数函数
a[1][0].plot(x, np.exp(x))
a[1][0].set_title('exp')
# 绘制对数函数
a[1][1].plot(x, np.log10(x))
a[1][1].set_title('log')
"""
# 绘制网络子图
"""
import matplotlib.gridspec as mg

mp.figure("Grid Layout", facecolor='lightgray')
gs = mg.GridSpec(3, 3)
mp.subplot(gs[0:2])
mp.text(0.5, 0.5, '1', size=36, alpha=0.6, ha='center', va='center')
mp.xticks([])
mp.yticks([])
mp.tight_layout()

mp.subplot(gs[:2, -1])
mp.text(0.5, 0.5, '2', size=36, alpha=0.6, ha='center', va='center')
mp.xticks([])
mp.yticks([])
mp.tight_layout()

mp.subplot(gs[1, 1])
mp.text(0.5, 0.5, '3', size=36, alpha=0.6, ha='center', va='center')
mp.xticks([])
mp.yticks([])
mp.tight_layout()

mp.subplot(gs[1:, 0])
mp.text(0.5, 0.5, '4', size=36, alpha=0.6, ha='center', va='center')
mp.xticks([])
mp.yticks([])
mp.tight_layout()


mp.subplot(gs[-1:, 1:])
mp.text(0.5, 0.5, '5', size=36, alpha=0.6, ha='center', va='center')
mp.xticks([])
mp.yticks([])
mp.tight_layout()
"""

# 刻度定位器
"""
ax = mp.gca()
# 不设置刻度 mp.NullLocator()  #set_major_locator 主刻度 #set_minor_locator#次刻度
ax.xaxis.set_major_locator(mp.NullLocator())  # 主刻度
ax.xaxis.set_major_locator(mp.MultipleLocator(0.5))  # 主刻度
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))  # 多点刻度器

其它刻度#
'mp.NullLocator()',
'mp.MaxNLocator(nbins=4)',
'mp.FixedLocator([3,6,9])',
'mp.AutoLocator()'
]
"""

# 自由布局
"""
mp.figure("flow layout")
mp.axes([0.03, 0.5, 0.94, 0.4])
mp.text(0.5, 0.5, "1")
mp.axes([0.03, 0.2, 0.24, 0.2])
mp.text(0.5, 0.5, "2")

"""
# 网络线示例
"""
mp.figure('gird Line', facecolor='lightgray')
ax = mp.gca()
ax.xaxis.set_major_locator(mp.MultipleLocator(1))
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))
ax.yaxis.set_major_locator(mp.MultipleLocator(250))
ax.yaxis.set_minor_locator(mp.MultipleLocator(10))
ax.grid(color='red', axis='both', linewidth=0.75)
y = [1, 10, 100, 1000, 10, 1]
mp.semilogy(y, '-o', color='dodgerblue')
"""
# 散点图
"""
n = 300
height = np.random.normal(175, 5, n)
weight = np.random.normal(70, 7, n)
d = (height - 175) ** 2 + (weight - 70) ** 2
mp.figure('Persons', facecolor='lightgray')
mp.title('Person', fontsize=18)
mp.xlabel('height', fontsize=14)
mp.ylabel('weight', fontsize=14)
mp.grid(linestyle=":")
mp.scatter(
    height, weight,

    marker='o',  # 点型
    s=10,  # 大小
    # color='',  # 颜色
    # edgecolors='',  # 边缘颜色
    # facecolor='',  # 填充色
    # zorder=''  # 图层序号
    label="personsabcd",
    c=d, cmap='Reds_r'  # Reds_r
)
mp.legend()
"""
# 填充
"""
x = np.linspace(0, 8 * np.pi, 1000)
sinx = np.sin(x)
cosx = np.cos(x / 2) / 2
mp.figure('Fill', facecolor='lightgray')
mp.title('Fill', fontsize=18)
mp.ylim(-1, 2)
mp.grid(linestyle=':')
mp.plot(x, sinx, color='dodgerblue', label=r'$sin(x)$')
mp.plot(x, cosx, color='orangered', label=r'$\frac{1}{2}cos(\frac{x}{2})$')
mp.fill_between(x, sinx, cosx, sinx > cosx, color='dodgerblue', alpha=0.3)
mp.fill_between(x, sinx, cosx, sinx < cosx, color='orangered', alpha=0.3)
mp.legend()
"""
# 柱状图
"""
apples = np.random.randint(1, 100, 20)
oranges = np.random.randint(1, 100, 20)
mp.figure('Bar', facecolor='lightgray')
mp.title('bar chart', fontsize=18)
mp.grid(linestyle=':')
x = np.arange(apples.size)
mp.bar(x - 0.2, apples, 0.4, align='center', color='limegreen', label="Apple")
mp.bar(x + 0.2, oranges, 0.4, align='center', color='orangered', label="orange")
mp.xticks(x, np.arange(20))
mp.legend()
"""

# 扇形图
"""
mp.figure('pie', facecolor='lightgray')
mp.axis('equal')  # 设置XY轴等比例输出
mp.pie(
    [26, 17, 21, 29, 11],  # 值列表
    explode=[0.02, 0.01, 0.05, 0.01, 0.01, ],  # 间距
    labels=['python', 'java', 'c++', 'php', 'Python'],  # 标签列表
    colors=['blue', 'red', 'green', 'orange', 'black'],  # 颜色列表
    autopct='%.1f%%',  # 占比显示格式
    shadow=True,  # 是否显示阴影
    startangle=90,  # 逆时针起始角度
    radius=1  # 半径
)

"""
# 等高线
"""
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)

mp.figure('Contour', facecolor='lightgray')
mp.title('Contour', fontsize=16)
mp.grid(linestyle=':')

cntr = mp.contour(x, y, z, 8, linewidths=0.5)# 普通模式
mp.clabel(cntr, inline_spacing=20, fontsize=10, fmt='%.2f')
cntr = mp.contourf(x, y, z, 8, cmap='jet')  # 填充模式
"""
# 热成像图
"""
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
mp.imshow(z, cmap='jet', origin='lower')
mp.colorbar()
"""
# 极坐标
"""
import matplotlib.pyplot as plt
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2])  # Less radial ticks
ax.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
ax.grid(True)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()
"""
# 生成动画 冒泡
"""
import matplotlib.animation as ma


def update(number):
    index = number % 100
    balls['position'][index] = np.random.uniform(0, 1, (1, 2))
    balls['size'][index] = np.random.uniform(50, 70, 1)
    balls['size'] += balls['growth']
    sc.set_sizes(balls['size'])
    sc.set_offsets(balls['position'])


ball_type = {'names': ['position', 'size', 'growth', 'color'],
             'formats': ['2f', 'f', 'f', '4f']}

n = 100
balls = np.zeros(100, dtype=ball_type)
balls['position'] = np.random.uniform(0, 1, (n, 2))
balls['size'] = np.random.uniform(50, 70, n)
balls['growth'] = np.random.uniform(10, 20, n)
balls['color'] = np.random.uniform(0, 1, (n, 4))
mp.figure('Animation', facecolor='lightgray')
mp.title('AN', fontsize=16)
mp.xticks([])
mp.yticks([])
sc = mp.scatter(balls['position'][:, 0], balls['position'][:, 1], s=balls['size'], color=balls['color'])
anim = ma.FuncAnimation(mp.gcf(), update, interval=30)
mp.show()
"""
# 生成动画 心电图
"""

import matplotlib.animation as ma

mp.figure('Signal', facecolor='lightgray')
mp.title("xindiantu", fontsize=14)
mp.xlim(0, 10)
mp.ylim(-3, 3)
mp.grid(linestyle=':', color='red', alpha=0.5)
pl, = mp.plot([], [], color='dodgerblue', label='XDT')
pl.set_data([], [])
x = 0


def y_generator():
    global x
    y = np.sin(2 * np.pi * x) * np.exp(np.sin(0.2 * np.pi * x))
    yield (x, y)
    x += 0.05


def update(data):
    t, v = data
    x, y = pl.get_data()
    x.append(t)
    y.append(v)
    pl.set_data(x, y)
    if x[-1] > 10:
        mp.xlim(x[-1] - 5, x[-1])


anim = ma.FuncAnimation(
    mp.gcf(), update, y_generator, interval=10)
mp.tight_layout()
mp.show()

"""

你可能感兴趣的:(matplotlib,python,开发语言)