依稀记得研究的那年互联网不发达,官方文档粗制滥造,不知道掉多少次坑,报过无数次错,但就是喜欢研究、琢磨,慢慢的也就这么过出来了。正所谓赠人玫瑰手留余香,附上代码及注释,希望对后来的你有所帮助,更希望您的关注和点赞!,感谢。
-
Matplotlib(一)
曲线,直线,标签,以前坐标轴偏移,和图例练习
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# 定义点
x = np.linspace(-3, 3, 50)
# 定义线
y1 = 2*x + 1
y2 = x**2
# plt.figure()
# plt.plot(x,y1)
# 定义窗体
plt.figure(num=3, figsize=(8,5))
# 定义轴长
plt.xlim((-1,2))
plt.ylim((-2,3))
# 定义轴名
plt.xlabel('xlabel')
plt.xlabel('ylabel')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# 定义轴点替换标签
plt.yticks([-2, -1.6, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$',r'$normal\ \alpha$',r'$good$',r'$really\ good$'])
# gca = "get current axis"
# 脊梁偏移
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', -.5))
ax.spines['left'].set_position(('data',0))
# outward, axes
l1, = plt.plot(x,y2,label = 'up', color = 'b', alpha = 0.7 )
l2, = plt.plot(x,y1,color = 'red',alpha = 0.7, linewidth = 1.0, linestyle = '--', label='down')
# 传参到handles里必须复制后加上','
# 定义图例
# labels会替换掉线性的label
plt.legend(handles=[l1, l2], labels=['blue line', 'red line'], loc= 'best')
plt.show()
-
Matplotlib(二)
再来一发,注解都在代码中里面只是一些常规参数,相信字面意思应该可以理解,自己复制下代码调下参数就都懂了
单直线,注释及图例练习~
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.figure(num=1, figsize=(8,5))
y1 = 2*x + 1
l1, = plt.plot(x,y1, alpha=0.7, color='b')
# 脊梁偏移
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
# 定义注释点
p1 = plt.scatter(x0, y0, s= 50 , c='r')
# 定义注释点至坐标的线
plt.plot([x0,x0],[y0, 0],'k--',lw=2.0)
# method 1
###############################
# 定义注释
plt.annotate(
# 注释文本
r'$2x + 1 = %s$'% y0,
# 注释以当前data为中心
xy=(x0,y0), xycoords='data',
# 注释偏移
xytext=(+30,-30), textcoords='offset points', fontsize=15 ,
# 注释图形,注释弧度等
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')
)
# method 2
###############################
plt.text(-4.0,3, r'$This\ is\ the\ some\ tag.\ \t\mu\ \sigma_i\ \alpha_t$',
fontdict={'size':16, 'color':'y'})
# 定义图例
plt.legend(handles=[p1, l1,], labels=['point', 'line',], loc= 'best')
plt.show()
-
Matplotlib(三)
很简单的一个线性图
plt.figure(figsize=(8,6))
samples = np.arange(0, 1.1, 0.1)
for i in samples:
plt.plot([0, 10], [0, i], label='gray-level %s'%i, lw=3,
color=str(i)) # ! gray level has to be parsed as string
plt.legend(loc='upper left')
plt.title('gray-levels')
plt.show()
-
Matplotlib(四)
结合入门1,入门2代码,综合制作双曲线图,详细说明见入门1、入门2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 5), dpi=80)
plt.subplot(111)
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")
ax = plt.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.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.yticks([-1, 1],
[r'$-1$', r'$+1$'])
plt.legend(loc='upper left')
t = 2*np.pi/3
plt.plot([t, t], [0, np.cos(t)],
color='blue', linewidth=1.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.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"))
plt.plot([t, t], [0, np.sin(t)],
color='red', linewidth=1.5, linestyle="--")
plt.scatter([t, ], [np.sin(t), ], 50, color ='red')
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7 ))
plt.show()
-
Matplotlib(五)
通过artan函数合成颜色,再通过marker调整点的形状,就做出酷炫的散点图了
n =1024
x = np.random.normal(0,1,n)
y = np.random.normal(0,1,n)
# for color value 色彩数量值
t = np.arctan2(y,x)
plt.figure(figsize=(8, 5), dpi=80)
# 主要方程式(x,y坐标,形状,透明度)
plt.scatter(x,y,s=75,c=t,marker='+',alpha=.5)
# plt.scatter(np.arange(5),np.arange(5))
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
plt.show()
-
Matplotlib(六)
最简单也最常用的柱状图,用随机数组形成正负两面柱状
plt.figure(figsize=(8, 5), dpi=80)
n =12
X = 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)
a = plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
b = plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x, y in zip(X ,Y1):
# ha:横向对其, va: 纵向对齐
plt.text(x ,y + 0.05,'%.2f'% y,ha='center',va='bottom')
for x, y in zip(X, Y2):
# ha:横向对其, va: 纵向对齐
plt.text(x ,- y - 0.05,'-%.2f'% y,ha='center',va='top')
plt.xlim(-0.5,n)
plt.xticks(())
plt.ylim(-1.25,1.25)
plt.yticks(())
plt.show()