更多编程教程请到:菜鸟教程 https://www.piaodoo.com/
友情链接:好看站 http://www.nrso.net/
简单演示
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
print(x)
y = 2*x + 1
plt.plot(x, y)
plt.show()
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y = 2**x + 1
plt.plot(x, y)
plt.show()
显示多个图像
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure()
plt.plot(x, y1)
plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1,
color=‘red’, # 线颜色
linewidth=1.0, # 线宽
linestyle=’–’ # 线样式
)
plt.show()
这里会显示两个图像:
去除边框,指定轴的名称
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure()
plt.plot(x, y1)
plt.xlabel(“I am x”)
plt.ylabel(“I am y”)
plt.show()
同时绘制多条曲线
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1,
color=‘red’, # 线条的颜色
linewidth=1.0, # 线条的粗细
linestyle=’–’ # 线条的样式
)
plt.xlim((-1, 2)) # x参数范围
plt.ylim((1, 3)) # y参数范围
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r’ r e a l l y b a d really\ bad really bad’, r’ b a d bad bad’, r’ n o r m a l normal normal’, r’ g o o d good good’, r’ r e a d l y g o o d readly\ good readly good’])
ax = plt.gca()
ax.spines[‘right’].set_color(‘none’)
ax.spines[‘top’].set_color(‘none’)
ax.xaxis.set_ticks_position(‘bottom’)
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘bottom’].set_position((‘data’, 0))
ax.spines[‘left’].set_position((‘data’, 0))
plt.show()
多条曲线之曲线说明
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure(num = 3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color=‘red’, linewidth=1.0, linestyle=’–’)
plt.xlim((-1, 2))
plt.ylim((1, 3))
plt.xlabel(“I am x”)
plt.ylabel(“I am y”)
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22,3],
[r’ r e a l l y b a d really\ bad really bad’, r’ b a d bad bad’, r’ n o r m a l normal normal’, r’ g o o d good good’, r’ r e a d l y g o o d readly\ good readly good’])
l1, = plt.plot(x, y2,
label=‘aaa’
)
l2, = plt.plot(x, y1,
color=‘red’, # 线条颜色
linewidth = 1.0, # 线条宽度
linestyle=’-.’, # 线条样式
label=‘bbb’ #标签
)
plt.legend(handles=[l1, l2],
labels = [‘aaa’, ‘bbb’],
loc = ‘best’
)
plt.show()
多个figure,并加上特殊点注释
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
plt.figure(figsize=(12, 8)) # 第一个参数表示的是编号,第二个表示的是图表的长宽
plt.plot(x, y2)
plt.plot(x, y1, color=‘red’, linewidth=1.0, linestyle=’–’)
ax = plt.gca()
ax.spines[‘right’].set_color(‘none’)
ax.spines[‘top’].set_color(‘none’)
ax.xaxis.set_ticks_position(‘bottom’)
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘bottom’].set_position((‘data’, 0))
ax.spines[‘left’].set_position((‘data’, 0))
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0, y0, s = 66, color = ‘b’)
plt.plot([x0, x0], [y0, 0], ‘k-.’, lw= 2.5)
plt.annotate(r’ 2 x + 1 = 2x+1=%s 2x+1=’ %
y0,
xy=(x0, y0),
xycoords=‘data’,
xytext=(+30, -30),
textcoords='offset points',
fontsize=16, # 这里设置的是字体的大小
# 这里设置的是箭头和箭头的弧度
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')
)
plt.text(0, 3,
r’ T h i s i s a g o o d i d e a . μ σ i α t This\ is\ a\ good\ idea.\ \mu\ \sigma_i\ \alpha_t This is a good idea. μ σi αt’,
fontdict={‘size’:16,‘color’:‘r’})
plt.show()
tick能见度设置
import matplotlib.pyplot as plt import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x - 1
plt.figure(figsize=(12, 8)) # 第一个参数表示的是编号,第二个表示的是图表的长宽
plt.plot(x, y, color=‘r’, linewidth=10.0, alpha=0.5)
ax = plt.gca()
ax.spines[‘right’].set_color(‘none’)
ax.spines[‘top’].set_color(‘none’)
ax.xaxis.set_ticks_position(‘bottom’)
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘bottom’].set_position((‘data’, 0))
ax.spines[‘left’].set_position((‘data’, 0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor=‘y’, edgecolor=‘None’, alpha=0.7))
plt.show()
多条曲线通用例子
def init_colors(): return ['blue', 'red', 'green', 'black', 'pink', 'purple', 'gray', 'yellow']
def show_graph(data, save_png_name=None, colors=init_colors()):
“”"
绘制折线图
:param data: 数据格式:{label:{X:Y}, label:{X:Y}…}
:param save_png_name:保存的图片的名字
:param colors: 颜色列表
:return:
None
“”"
my_font = font_manager.FontProperties(fname="/自己补充路径/IOS8.ttf")
plt.figure(figsize=(14, 6))
plts = []
labels = []
for index, label in enumerate(data.keys()):
if label is ‘rotate’:
continue
color = colors[index]
X = data.get(label).keys()
Y = [data.get(label).get(x) for x in X]
temp, = plt.plot(X, Y, color=color, label=label)
plts.append(temp)
labels.append(label)
plt.legend(handles=plts, labels=labels, prop=my_font)
plt.show()
if save_png_name is not None:
plt.savefig(save_png_name)
散点图
import matplotlib.pyplot as plt import numpy as np
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y)
plt.scatter(np.arange(5), np.arange(5))
plt.xticks(())
plt.yticks(())
plt.show()
条形图
import matplotlib.pyplot as plt import numpy as np
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.figure(figsize=(12, 8))
plt.bar(X, +Y1, facecolor=’#9999ff’, edgecolor=‘white’)
plt.bar(X, -Y2, facecolor=’#ff9999’, edgecolor=‘white’)
for x, y in zip(X,Y1):
plt.text(x, y+0.05, ‘%.2f’ % y, ha=‘center’, va=‘bottom’)
for x, y in zip(X,-Y2):
plt.text(x, y-0.05, ‘%.2f’ % y, ha=‘center’, va=‘top’)
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
plt.show()
contour等高线图
import matplotlib.pyplot as plt import numpy as np
def get_height(x, y):
return (1-x/2+x5+y3)*np.exp(-x2-y2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
plt.figure(figsize=(14, 8))
plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot)
C = plt.contour(X, Y, get_height(X, Y), 16, color=‘black’, linewidth=.5)
plt.clabel(C, inline=True, fontsize=16)
plt.xticks(())
plt.yticks(())
plt.show()
image图片显示
import matplotlib.pyplot as plt import numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
“”"
for the value of “interpolation”, check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of “origin”= [‘upper’, ‘lower’], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
“”"
plt.imshow(a, interpolation=‘nearest’, cmap=‘bone’, origin=‘lower’)
plt.colorbar(shrink=.90) # 这是颜色深度的标注,shrink表示压缩比例
plt.xticks(())
plt.yticks(())
plt.show()
3D数据图
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X,Y = np.meshgrid(X, Y)
R = np.sqrt(X2 + Y2)
Z = np.sin®
ax.plot_surface(X, Y, Z,
rstride=1, # 行的跨度
cstride=1, # 列的跨度
cmap=plt.get_cmap(‘rainbow’) # 颜色映射样式设置
)
ax.contourf(X, Y, Z, zdir=‘z’, offest=-2, cmap=‘rainbow’)
ax.set_zlim(-2, 2)
plt.show()
Subplot多合一显示
import matplotlib.pyplot as plt import numpy as np
plt.figure()
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(222)
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()
分格显示
subplot2grid
import matplotlib.pyplot as plt import numpy as np import matplotlib.gridspec as gridspec
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2])
ax1.set_title(r’ a x 1 _ t i t l e ax1\_title ax1_title’)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax2.set_title(r’ a x 2 _ t i t l e ax2\_title ax2_title’)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax3.set_title(r’ a x 3 _ t i t l e ax3\_title ax3_title’)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.set_title(r’ a x 4 _ t i t l e ax4\_title ax4_title’)
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax5.set_title(r’ a x 5 _ t i t l e ax5\_title ax5_title’)
plt.tight_layout()
plt.show()
gridspec
import matplotlib.pyplot as plt import numpy as np
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax1.set_title(r’ a x 1 _ t i t l e ax1\_title ax1_title’)
ax2 = plt.subplot(gs[1, :2])
ax2.set_title(r’ a x 2 _ t i t l e ax2\_title ax2_title’)
ax3 = plt.subplot(gs[1:, 2])
ax3.set_title(r’ a x 3 _ t i t l e ax3\_title ax3_title’)
ax4 = plt.subplot(gs[-1, 0])
ax4.set_title(r’ a x 4 _ t i t l e ax4\_title ax4_title’)
ax5 = plt.subplot(gs[-1, -2])
ax5.set_title(r’ a x 5 _ t i t l e ax5\_title ax5_title’)
plt.tight_layout()
plt.show()
easy to define structure分格显示
import matplotlib.pyplot as plt import numpy as np
plt.figure()
f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1, 2], [1, 2])
ax11.set_title(‘11’)
ax12.set_title(‘11’)
ax21.set_title(‘21’)
ax22.set_title(‘22’)
plt.tight_layout()
plt.show()
图中图
import matplotlib.pyplot as plt import numpy as np
fig = plt.figure(figsize=(10, 6))
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, weight = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, weight])
ax1.plot(x, y, ‘r’)
ax1.set_xlabel(r’ x x x’)
ax1.set_ylabel(r’ y y y’)
ax1.set_title(r’ × × I n t e r e s t i n g × × ××Interesting×× ××Interesting××’)
left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, weight])
ax2.plot(y, x, ‘b’)
ax2.set_xlabel(r’ x x x’)
ax2.set_ylabel(r’ y y y’)
ax2.set_title(r’ t i t l e i n s i d e 1 title\ inside\ 1 title inside 1’)
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1],x, ‘g’)
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.title(r’ t i t l e i n s i d e 2 title\ inside\ 2 title inside 2’)
plt.show()
主次坐标轴
import matplotlib.pyplot as plt import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, ‘g-’)
ax2.plot(x, y2, ‘b–’)
ax1.set_xlabel(r’ X d a t a X\ data X data’, fontsize=16)
ax1.set_ylabel(r’ Y 1 Y1 Y1’, color=‘g’, fontsize=16)
ax2.set_ylabel(r’ Y 2 Y2 Y2’, color=‘b’, fontsize=16)
plt.show()
Animation动画
import matplotlib.pyplot as plt import numpy as np 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/100))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig,
func=animate, # 动画函数
frames=100, # 帧数
init_func=init, # 初始化函数
interval=20, # 20ms
blit=True)
plt.show()
到此这篇关于Python Matplotlib简易教程(小白教程)的文章就介绍到这了,更多相关Python Matplotlib简易教程内容请搜索菜鸟教程www.piaodoo.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持菜鸟教程www.piaodoo.com!