mathplot.pyplot的画图操作。
import matplotlib.pyplot as plt
import math
import numpy as np
#绘制折线图
squares = [1, 2, 3, 4, 45]
input_values = [2, 5, 4, 23, 45]
plt.plot(input_values, squares, linewidth=5)
plt.title('ssquare numbers', fontsize=14)
plt.xlabel('value', fontsize=14)
plt.ylabel('square of value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.show()
#绘制散点图
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, cmap=plt.cm.Blues, s=100)
plt.title('square numbers', fontsize=14)
plt.xlabel('value', fontsize=14)
plt.ylabel('square of value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
x = np.arange(1, 5, 0.1)
plt.plot(x, x, 'r-', x, x*x, 'go', x, x*x*x, 'm^')
plt.text(1.5, 100, '$add text$')
plt.axis([1, 5, 0, 125])
plt.show()
#绘制柱状图
plt.bar(left=(1, 2, 3, 4), height=(2, 3, 1, 5), width=0.5, align='center', yerr=0.1, color='grey')
plt.show()
#绘制散点图
n = 1024
plt.scatter(np.random.normal(0, 1, n), np.random.normal(0, 1, n))
plt.show()
#等高线
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet')
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
plt.show()
#3d图片
#直方图
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=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$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
#文本注释
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()
#添加图例
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left')
plt.show()
#axes和subplot
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax2 = fig.add_axes([0.72, 0.72, 0.16, 0.16])
plt.show()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
plt.show()
#图片中显示数学公式
def f(x, c):
m1 = np.sin(2*math.pi*x)
m2 = np.exp(-c*x)
return np.multiply(m1, m2)
x = np.linspace(0, 4, 100)
sigma = 0.5
plt.plot(x, f(x, sigma), 'r', linewidth=2)
plt.xlabel(r'$\rm{time} \ t$', fontsize=16)
plt.ylabel(r'$\rm{Amplitude} \ f(x)$', fontsize=16)
plt.title(r'$f(x) \ \rm{is \ damping \ with} \ x$', fontsize=16)
plt.text(2.0, 0.5, r'$f(x) = \rm{sin}(2 \pi x^2) e^{\sigma x}$', fontsize=20)
plt.savefig('latex.png', dpi=75)
plt.show()