郑重说明:本菜鸟参考简书writ大神:https://www.jianshu.com/p/6027db4a0d2f和菜鸟编程中文文档所写!
一,学习matplotlib绘图
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(1, 11)
print(x)
y = 2 * x + 5
print(y)
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x, y)
plt.show()
np.arange() 函数创建 x 轴上的值。y 轴上的对应值存储在另一个数组对象 y 中。 这些值使用 matplotlib 软件包的 pyplot 子模块的 plot() 函数绘制。图形由 show() 函数显示。
二,系统字体
from matplotlib import pyplot as plt
import matplotlib
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
三,换颜色形状
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(1, 11)
y = 2 * x + 5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x, y, "ob")
plt.show()
四,绘制正弦波
import numpy as np
import matplotlib.pyplot as plt
# 计算正弦曲线上点的 x 和 y 坐标
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.title("sine wave form")
# 使用 matplotlib 来绘制点
plt.plot(x, y)
plt.show()
五,subplot()函数
subplot() 函数允许你在同一图中绘制不同的东西
import numpy as np
import matplotlib.pyplot as plt
# 计算正弦和余弦曲线上的点的 x 和 y 坐标
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# 建立 subplot 网格,高为 2,宽为 1
# 激活第一个 subplot
plt.subplot(2, 1, 1)
# 绘制第一个图像
plt.plot(x, y_sin)
plt.title('Sine')
# 将第二个 subplot 激活,并绘制第二个图像
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
# 展示图像
plt.show()
六,bar()函数 条形图
pyplot 子模块提供 bar() 函数来生成条形图。
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.bar(x, y, align = 'center')
plt.bar(x2, y2, color = 'g', align = 'center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
七,plt() 直方图
from matplotlib import pyplot as plt
import numpy as np
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
plt.hist(a, bins=[0, 20, 40, 60, 80, 100])
plt.title("histogram")
plt.show()
八,扇形图 pie
import matplotlib.pyplot as mp
mp.figure('pie', facecolor='lightgray')
#整理数据
values = [26, 17, 21, 29, 11]
spaces = [0.01, 0.01, 0.01, 0.01, 0.01]
labels = ['Python', 'JavaScript',
'C++', 'Java', 'PHP']
colors = ['dodgerblue', 'orangered',
'limegreen', 'violet', 'gold']
mp.figure('Pie', facecolor='lightgray')
mp.title('Pie', fontsize=20)
# 等轴比例
mp.axis('equal')
mp.pie(
values, # 值列表
spaces, # 扇形之间的间距列表
labels, # 标签列表
colors, # 颜色列表
'%d%%', # 标签所占比例格式
shadow=True, # 是否显示阴影
startangle=90, # 逆时针绘制饼状图时的起始角度
radius=1 # 半径
)
mp.show()
九,等高线图
import numpy as np
import matplotlib.pyplot as mp
n = 1000
# 生成网格化坐标矩阵
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
# 根据每个网格点坐标,通过某个公式计算z高度坐标
z = (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
mp.figure('Contour', facecolor='lightgray')
mp.title('denggaoxian', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
# 绘制等高线图
mp.contourf(x, y, z, 8, cmap='jet')
cntr = mp.contour(x, y, z, 8, colors='black',
linewidths=0.5)
# 为等高线图添加高度标签
mp.clabel(cntr, inline_spacing=1, fmt='%.1f',
fontsize=10)
mp.show()
十,散点图
import numpy as np
import matplotlib.pyplot as mp
n = 100
# 172: 期望值
# 10: 标准差
# n: 数字生成数量
x = np.random.normal(172, 20, n)
y = np.random.normal(60, 10, n)
mp.figure('scatter', facecolor='lightgray')
mp.title('scatter')
# mp.scatter(x, y)
mp.scatter(x, y, c='red') #直接设置颜色
d = (x-172)**2 + (y-60)**2
mp.scatter(x, y, c=d, cmap='jet') #以c作为参数,取cmap颜色映射表中的颜色值
mp.show()
十一,3D图
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
mp.figure('3D Scatter')
ax = mp.gca(projection='3d') # 创建三维坐标系
mp.title('3D Scatter', fontsize=20)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.scatter(x, y, z, s=60, c=d, cmap='jet_r', alpha=0.5)
mp.show()
十二,极坐标图
import numpy as np
import matplotlib.pyplot as mp
mp.figure('Polar', facecolor='orangered')
mp.gca(projection='polar')
mp.title('Polar')
mp.xlabel(r'$\theta$', fontsize=14)
mp.xlabel(r'$\rho$', fontsize=14)
mp.grid(linestyle=':')
# 绘制线性关系
# t = np.linspace(0, 4*np.pi, 1000)
# r = 0.8*t
# mp.plot(t, r)
# mp.show()
# 绘制sin曲线
x = np.linspace(0, 6*np.pi, 1000)
y = 3*np.sin(6*x)
mp.plot(x, y)
mp.show()
十三,3D平面图
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
# 生成网格化坐标矩阵
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
# 根据每个网格点坐标,通过某个公式计算z高度坐标
z = (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
mp.figure('3D', facecolor='lightgray')
ax3d = mp.gca(projection='3d')
mp.title('3D', fontsize=20)
# ax3d.set_xlabel('x', fontsize=14)
# ax3d.set_ylabel('y', fontsize=14)
# ax3d.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
# 绘制3D平面图
# rstride: 行跨距
# cstride: 列跨距
ax3d.plot_surface(x, y, z, rstride=10, cstride=10, cmap='jet')
mp.show()
十四,sin(),cos()
import numpy as np
import matplotlib.pyplot as mp
n = 1000
x = np.linspace(0, 8 * np.pi, n)
sin_y = np.sin(x)
cos_y = np.cos(x / 2) / 2
mp.figure('Fill', facecolor='lightgray')
mp.title('Fill', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.plot(x, sin_y, c='dodgerblue',
label=r'$y=sin(x)$')
mp.plot(x, cos_y, c='orangered',
label=r'$y=\frac{1}{2}cos(\frac{x}{2})$')
mp.fill_between(x, cos_y, sin_y, cos_y < sin_y,
color='dodgerblue', alpha=0.5)
mp.fill_between(x, cos_y, sin_y, cos_y > sin_y,
color='orangered', alpha=0.5)
mp.legend()
mp.show()
十五,生成动画泡泡
# 生成动画泡泡
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
# 构建100个泡泡,确定属性
n = 100
balls = np.zeros(100, dtype=[
('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
# 初始化所有ball的属性值
# 随机生成最小值为0,最大值为1的N行2列的数组
# 初始化所有ball图标
balls['position'] = np.random.uniform(0, 1, (n, 2))
balls['size'] = np.random.uniform(40, 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('Animation', fontsize=16)
mp.xticks([])
mp.yticks([])
sc = mp.scatter(balls['position'][:, 0], balls['position'][:, 1], balls['size'], color=balls['color'])
def update(number):
# 定义更新图像
balls['size'] += balls['growth']
# 让某个球重新初始化属性
ind = number % n
balls[ind]['size'] = np.random.uniform(40, 70, 1)
balls[ind]['position'] = np.random.uniform(0, 1, (1, 2))
sc.set_sizes(balls['size'])
sc.set_offsets(balls['position'])
anim = ma.FuncAnimation(mp.gcf(), update, interval=30)
mp.show()