matplotlib简单使用

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 2 * np.pi, 0.1)
# y = np.sin(x)
# plt.title("sin(x)")
# plt.xlabel("x")
# plt.ylabel("y")
# plt.plot(x, y, 'o')  # 圆标记
# plt.show()

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() 函数来生成条形图
"""
x2 = [6, 9, 11]
y2 = [6, 15, 7]
plt.bar(x2, y2, color='g', align='center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

"""
频率分布
22,87,5,43,56,73,55,54,11,20,51,5,79,31,27
bins =  [0,20,40,60,80,100],水平尺寸相等的矩形对应于类间隔
[3 4 5 2 1]
[0-20) ->3个
"""
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
hist, bins = np.histogram(a, bins=[0, 20, 40, 60, 80, 100])
print(hist)  # [3 4 5 2 1]
print(bins)  # [  0  20  40  60  80 100]
plt.hist(a, bins=[0, 20, 40, 60, 80, 100])
plt.title("histogram")
plt.show()

深入使用

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, ylim, xticks, yticks, xlim, legend, gca, annotate

figure(figsize=(9, 10), dpi=60)
X = np.linspace(-3 * np.pi, 3 * np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)

# 设置横轴的上下限
xlim((-3 * np.pi) // 1, (3 * np.pi) // 1)
# 设置横轴记号
# xticks(np.linspace((-3 * np.pi) // 1, (3 * np.pi) // 1, 20, endpoint=True))
xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
# 设置纵轴的上下限
ylim(-1.0, 1.0)
# 设置纵轴记号
yticks(np.linspace(-1, 1, 5, endpoint=True))

# 坐标轴线
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

plt.plot(X, C, color='green', linewidth=2.5, linestyle='--', label="cosine")
plt.plot(X, S, color='red', label="sine")
# 添加图例
legend(loc='upper left')

# 特殊点做注释
t = 2*np.pi/3
annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
         xy=(t, np.sin(t)), xycoords='data',
         xytext=(+10, +30), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

# 以分辨率 72 来保存图片
# savefig("exercice_2.png",dpi=72)
plt.show()
posted @ 2020-08-13 14:36  fly_bk  阅读(110)  评论(0编辑  收藏  举报