@nemos
2017-05-08T11:12:48.000000Z
字数 4931
阅读 1519
ml
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x ** 2
# 新建画布,一个画布对于了一个窗口
plt.figure()
# 以下绘图操作都会在这个创建的这个画布上呈现
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# 显示图像
plt.show()
# 再建一个画布
plt.figure()
# 同理
plt.plot(x, y1)
plt.show()
画布一
画布二
plt.figure()
# 设置坐标范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# 设置坐标名称
plt.xlabel('I am x')
plt.ylabel('I am y')
# 刻度设置
new_ticks = np.linspace(-1, 2, 5) # -1到2的五个刻度六个间距
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) # 文字刻度
# get current axis
ax = plt.gca() # 一个坐标有四个轴
# 获得右坐标轴
ax.spines['right'].set_color('none') # none使其不可见
ax.spines['top'].set_color('none')
# x轴设置成下坐标轴
ax.xaxis.set_ticks_position('bottom')
# 移动坐标轴使其在y=0的位置
ax.spines['bottom'].set_position(('data', 0))
# 可以在绘制时指定label
l1, = plt.plot(x, y2, label='linear line')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='square line')
# 指定图例的线,标签,和位置
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
# 绘制直线
plt.plot(x, y1)
# 设置要标注的点
x0 = 1
y0 = 2*x0 + 1
# 绘制标注的点
plt.scatter([x0, ], [y0, ], s=50, color='b')
# 到X轴的虚线
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# 绘制标注
plt.annotate(
r'$2x+1=%s$' % y0, # 要标注的文字
xytext=(+30, -30), # 文字的的位置
textcoords='offset points', # 文字位置的基准
xy=(x0, y0), # 标注的位置
xycoords='data', # 标注位置的基准
fontsize=16,
arrowprops=dict( # 箭头样式
arrowstyle='->',
connectionstyle="arc3,rad=.2"))
# 绘制文字
plt.text(
-3.7, 3, # 位置
r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$', # 文字
fontdict={'size': 16, 'color': 'r'}) # 字体
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
line, = ax.plot([0,1], [0,1])
ax.set_title("a straight line (OO)")
ax.set_xlabel("x value")
ax.set_ylabel("y value")
canvas.print_figure('demo.jpg')
注:canvas为画图的引擎,这里的层次指的是逻辑的层次
n = 1024 # 数据大小
# 正态分布生成
X = np.random.normal(0, 1, n) # 每一个点的X值
Y = np.random.normal(0, 1, n) # 每一个点的Y值
T = np.arctan2(Y,X) # for color value
plt.scatter(
X, Y,
s=75,
c=T, # 色彩map
alpha=.5) # 透明度
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticks
plt.show()
# 数据生成
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
# 设置颜色和正反向绘图
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
# 坐标设置
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
# 显示每个柱的数值
for x, y in zip(X, Y1):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
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)i
# 颜色填充
plt.contourf(
X, Y, f(X, Y), # 坐标
8, # 由等高线分成多少部分
alpha=.75, # 透明度
cmap=plt.cm.hot) # 颜色主题
# 等高线
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
# 在线上添加label
plt.clabel(C, inline=True, fontsize=10)
# 去掉坐标
plt.xticks(())
plt.yticks(())
pic = np.array(
[0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]
).reshape(3,3)
# 显示图片
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
# 添加标注
plt.colorbar(shrink=.92)
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
# 添加3D坐标轴
ax = Axes3D(fig)
# 数据生成
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
# x-y 平面的网格
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
# 生成曲面
ax.plot_surface(
X, Y, Z,
rstride=1, # row栅格的跨度
cstride=1, # column同上
cmap=plt.get_cmap('rainbow')) # 色彩主题
ax.contourf(
X, Y, Z,
zdir='z', # 指定从Z轴的投影
offset=-2,
cmap=plt.get_cmap('rainbow'))
plt.show()
plt.figure()
# 创建子画布
plt.subplot(2,2,1) # 画第一个子画布
plt.plot([0,1],[0,1])
plt.subplot(2,2,2) # 画第二个子画布
plt.plot([0,1],[0,2])
plt.subplot(223)
plt.plot([0,1],[0,3])
plt.subplot(224)
plt.plot([0,1],[0,4])
plt.show()
plt.figure()
# 创建子画布
plt.subplot(2,1,1) # 使第一个画布占满第一行的三列
plt.plot([0,1],[0,1])
plt.subplot(2,3,4) # 从第四个格子开始排
plt.plot([0,1],[0,2])
plt.subplot(235)
plt.plot([0,1],[0,3])
plt.subplot(236)
plt.plot([0,1],[0,4])
plt.show()
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# 绘制大图
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
# 绘制小图
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
from matplotlib import animation
fig, ax = plt.subplots()
# 生成正弦曲线
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
# 定义动画函数,接受一个帧数参数
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
# 开始帧
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(
fig=fig, # 指定figure
func=animate, # 动画函数
frames=100, # 动画长度
init_func=init, # 开始帧
interval=20, # 更新频率,ms为单位
blit=False) # mac用false
plt.show()
# 保存动画
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
莫烦python-Matplotlib
绘图: matplotlib核心剖析
matplotlib - 2D and 3D plotting in Python
利用plotly for Python进行数据可视化