自用的matplotlib代码

base

plt.title(r'宋体 $\mathrm{Times \; New \; Roman}\/\/ \alpha_i > \beta_i$')

plot1

import matplotlib.pyplot as plt
import numpy as np

# make data
boxcell_x = np.concatenate([np.arange(0, 4) * 1.5 + 4.2, np.arange(0, 2) * 1.5 + 7.2])  # np.array([])
boxcell_y = np.concatenate([np.ones(4) * 2.6, np.ones(2) * 4.1])

circell_x = np.array([2.7, 4.2, 5.7, 7.2, 8.7])
circell_y = np.array([2.6, 4.1, 4.1, 5.6, 5.6])

dotcell_x = np.array([2.7, 4.2, 2.7, 4.2, 5.7, 7.2, 8.7])
dotcell_y = np.array([5.6, 5.6, 7.2, 7.2, 7.2, 7.2, 7.2])

shodow_x = np.array([4.2, 4.2, 5.7, 5.8])
shodow_y = np.array([5.6, 7.2, 7.2, 5.5])

crosscell_x = np.array([2.5, 5.55])
crosscell_y = np.array([4.3, 5.89])

sdotcell_x = np.array([5.3, 5.8])
sdotcell_y = np.array([6.3, 5.5])

# plot marks
plt.plot(circell_x, circell_y, marker=r'$\bigodot$', markersize=22,
         linewidth=0, alpha=0.6, color='k', label='Gost-Cell')
plt.plot(boxcell_x, boxcell_y, marker=r'$\boxdot$', markersize=22,
         linewidth=0, alpha=0.6, color='k', label='Solid-Cell')
plt.plot(dotcell_x, dotcell_y, marker='o', markersize=12, linewidth=0,
         alpha=0.5, color='k', label='Fluid-Cell')
plt.plot(crosscell_x, crosscell_y, marker=r'$\oplus$', markersize=8,
         linewidth=0, label='Fresh-Cell')
plt.plot(sdotcell_x, sdotcell_y, marker=r'$\circ$', markersize=8,
         linewidth=1, alpha=0.8, color='k')
# plot shodow
plt.fill(shodow_x, shodow_y, linewidth=0, alpha=0.2, color='k')

plt.annotate('BI', xy=(5.8, 5.5), xytext=(+5, +5), textcoords='offset points')
plt.annotate('IP', xy=(5.3, 6.3), xytext=(+5, +5), textcoords='offset points')

# plot curve
plt.annotate(r'$n+1$',
             xy=(9.6, 6.5), xycoords='data',
             xytext=(1.4, 2.4), textcoords='data', fontsize=16,
             arrowprops=dict(arrowstyle="-", connectionstyle="arc3,rad=-.2"))
plt.annotate(r'$n$',
             xy=(9.4, 6.9), xycoords='data',
             xytext=(1.4, 3.5), textcoords='data', fontsize=16,
             arrowprops=dict(arrowstyle="-", connectionstyle="arc3,rad=-.2",
                             linestyle='dashed'))
plt.grid(True, color='k', linewidth=2)

# set the figure style
ax = plt.gca()

ax.set_xticks(np.arange(0, 10, 1.5) + 0.4)
ax.set_yticks(np.arange(0, 10, 1.5) + 0.4)

ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')

plt.axis('scaled')
plt.xlim(0.5, 10.5)
plt.ylim(-1, 9)
plt.tick_params(labelbottom='off', labelleft='off', left='off', right='off',
                bottom='off', top='off')

# add the legend
ax.legend(loc='lower center', handlelength=2.3, handletextpad=1, labelspacing=1,
          ncol=2, mode="expand", borderpad=1, fancybox=True)
plt.show()

在这里插入图片描述

plot2

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


# define a 3D arrow
class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
normal = np.array([0, 0, 1])

# the coordinate of axis plane
xx = np.array([[1, 0, -1],
               [1, 0, -1],
               [1, 0, -1]])
xy = np.array([[1, 1, 1],
               [0, 0, 0],
               [-1, -1, -1]])
zero = np.array([[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]])

ax.set_axis_off()

# plot axis plane
ax.plot_surface(xx, xy, zero, rstride=2, cstride=2, color='b', linewidth=0, alpha=0.3)
ax.plot_surface(xx, zero, xy, rstride=2, cstride=2, color='b', linewidth=0, alpha=0.3)
ax.plot_surface(zero, xx, xy, rstride=2, cstride=2, color='b', linewidth=0, alpha=0.3)

# add arrow
arrow = Arrow3D([0, 0], [0, 0], [-1, 1], mutation_scale=20, lw=1,
                arrowstyle="<|-|>", color="k", linestyle="solid")
ax.add_artist(arrow)
# add text
ax.text(0, 0, 1.1, '3', fontsize=14)
ax.text(0, 0, -1.1, '4', fontsize=14)

arrow = Arrow3D([0, 0], [-1, 1], [0, 0], mutation_scale=20, lw=1,
                arrowstyle="<|-|>", color="k", linestyle="solid")
ax.add_artist(arrow)
ax.text(0, 1.1, 0, '6', fontsize=14)
ax.text(0, -1.1, 0, '5', fontsize=14)

arrow = Arrow3D([-1, 1], [0, 0], [0, 0], mutation_scale=20, lw=1,
                arrowstyle="<|-|>", color="k", linestyle="solid")
ax.add_artist(arrow)
ax.text(1.1, 0, 0, '1', fontsize=14)
ax.text(-1.1, 0, 0, '2', fontsize=14)

arrow = Arrow3D([1, -1], [0, 0], [1, -1], mutation_scale=20, lw=1,
                arrowstyle="<|-|>", color='w', linestyle="dashed")
ax.add_artist(arrow)
ax.text(1.1, 0, 1.1, '10', fontsize=14)
ax.text(-1.1, 0, -1.1, '9', fontsize=14)

arrow = Arrow3D([1, -1], [0, 0], [-1, 1], mutation_scale=20, lw=1,
                arrowstyle="<|-|>", color='w', linestyle="dashed")
ax.add_artist(arrow)
ax.text(-1.1, 0, 1.1, '14', fontsize=14)
ax.text(1.1, 0, -1.1, '13', fontsize=14)

plt.show()

在这里插入图片描述

plot3

参数法–参数方程图像绘制

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as AA

fig = plt.figure(figsize=(14, 6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], axes_class=AA.Axes)
ax.axis['top','right','left','bottom'].set_visible(False)
ax.axis["x"] = ax.new_floating_axis(0, 0, axis_direction="bottom")
ax.axis["y"] = ax.new_floating_axis(1, 0, axis_direction="bottom")
ax.axis["x"].set_axisline_style("->", size=1.0)
ax.axis["y"].set_axisline_style("->", size=1.0)
ax.set_yticks([-1,1,1.5,2,3,4,5])
plt.xticks([ -1, 1, np.pi/2, np.pi, 2*np.pi, 4*np.pi],[r'$-1$', r'$1$', r'$+\pi/2$', r'$+\pi$', r'$+2\pi$', r'$+4\pi$'])
plt.xlim(-1, 15)
plt.ylim(-1, 5)

ax.annotate(r'$ \{ \genfrac{}{}{0}{}{ x\ =\ r\ t\  -\  r\ sin(t) }{ y\  =\  r\  -\  r\ cos(t) }$',xy=(10,3), xycoords='data',xytext=(-20,+30), textcoords='offset points', fontsize=30)
ax.text(-0.5, 5.5, 'y', fontsize=20)
ax.annotate(text='    x', xy=(15, 0), fontsize=20)
ax.grid(True, linestyle='-.')

r = 2
# t = np.linspace(0, 15, 1000)
t = np.linspace(-np.pi, 3 * np.pi, 1000)
x = r*(t-np.sin(t))
y = r*(1-np.cos(t))
plt.plot(x,y,color='b',linewidth=2,linestyle="-")

# r = 2: x∈[ox-2,ox+2] 
ox = 2.6 #*np.pi/4
oy = 2
plt.scatter(ox,oy, marker='.', edgecolors='blue', linewidth=2, s=100)

plt.scatter(ox+.2,2.2, marker='$C$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(ox+.4,2.2, marker='$‘$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(ox,0, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(ox-.2,-.2, marker='$Q$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(-.2,2.2, marker='$C$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(0,2, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(0,0, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(-.2,-.2, marker='$O$', edgecolors='blue', linewidth=2, s=200)

ax.plot([ox,ox],[0, 2], color ='orange', linewidth=3, linestyle=":")

x = np.linspace(ox-2, ox+2, 1000)

# r=2,circumference=4π,t = ox/2
# A 点坐标由 t 决定。圆心从 C 到 C' 过程中,点 A 走过的弧长即 OQ。此示例中∠AC'Q是锐角。由于角度比等于弧度比,
# OQ 与 四分之一圆弧的比 即是 ∠AC'Q 与 90°的比。
# 其中,由于四分之一圆弧长 π (2πr/4 = π),也可以先不带入r,
# OQ /(πr/2) = ∠AC'Q /(π/2) => ∠AC'Q = OQ/r,得 ∠AC'Q = OQ/2
px = r*(ox/2-np.sin(ox/2))
py = r*(1-np.cos(ox/2))

ax.annotate(r'$(x,y)$',xy=(px,py), xycoords='data',xytext=(+20, -30), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

plt.scatter(px,py, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(px-.2,py+.2, marker='$A$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(ox,py, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(ox+.2,py, marker='$D$', edgecolors='blue', linewidth=2, s=200)
plt.scatter(px,0, marker='.', edgecolors='blue', linewidth=2, s=100)
plt.scatter(px+.2,-.2, marker='$P$', edgecolors='blue', linewidth=2, s=200)

ax.plot([px,px],[0, py], color ='orange', linewidth=3, linestyle=":")
ax.plot([px,ox],[py, oy], color ='orange', linewidth=3, linestyle=":")
ax.plot([px,ox],[py, py], color ='violet', linewidth=3, linestyle="-")
ax.plot([ox,ox],[py, oy], color ='violet', linewidth=3, linestyle="-")

ax.annotate(r'$r * sin(t)$',xy=(2.3,py), xycoords='data',xytext=(+20, -50), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))
ax.annotate(r'$r * cos(t)$',xy=(ox,1.7), xycoords='data',xytext=(+30, +20), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

y = np.sqrt(4-(x-ox)**2)+2
plt.plot(x,y,color='r',linewidth=2,linestyle="-")
y = -np.sqrt(4-(x-ox)**2)+2
plt.plot(x,y,color='r',linewidth=2,linestyle="-")

x = np.linspace(px, ox, 1000)
y = -np.sqrt(4-(x-ox)**2)+2
plt.plot(x,y,color='g',linewidth=2,linestyle="-")
ax.plot([0,ox],[0, 0], color ='g', linewidth=3, linestyle="-")

ax.annotate(r'$r * t = OQ = \genfrac{}{}{0}{}{⌒}{AQ}$',xy=(1.2,-np.sqrt(2.04)+2), xycoords='data',xytext=(+150, -70), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

er=0.2
et = ox-np.sin(er)
x = np.linspace(et, ox, 1000)
y = -np.sqrt(er**2-(x-ox)**2)+2
plt.plot(x,y,color='cyan',linewidth=2,linestyle="-")
plt.scatter(ox-.3,oy-.3, marker='$t$', edgecolors='cyan', linewidth=2, s=100)

ax.plot([px,px],[0, py], color ='purple', linewidth=3, linestyle="-")
ax.annotate(r'$y = r - r * cos(t)$',xy=(px,0.7), xycoords='data',xytext=(+40, -90), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

ax.plot([0,px],[0, 0], color ='purple', linewidth=3, linestyle="-")
ax.annotate(r'$x = r * t - r * sin(t)$',xy=(0.2,0), xycoords='data',xytext=(-40, -90), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

ax.annotate(r'$(2\pi, 2r)$',xy=(2 * np.pi,2 * r), xycoords='data',xytext=(-0, -30), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))

ax.plot([2 * np.pi,2 * np.pi],[-1, 5], color ='violet', linewidth=3, linestyle="-.")
ax.annotate(r'$axis\ of\ symmetry( x = \pi r)$',xy=(2 * np.pi,2), xycoords='data',xytext=(-0, -30), textcoords='offset points', fontsize=16,
         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1"))
#ax.arrow(0,0,3,3)
plt.show()

在这里插入图片描述

plot4

零: python matplotlib 画图进阶(含完整代码)

import numpy as np
import matplotlib.pyplot as plt

# 生成2-D数据
X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
Cos, Sin = np.cos(X), np.sin(X)

# 这里显示调用了plt.figure返回一个fig对象, 为了能够后面保存这个fig对象
# 并且设置了fig的大小和每英寸的分辨率
# 注意: resolution = figsize*dpi(因此这里的savefig的分辨率为1200X900)
fig = plt.figure(figsize=(4,3),dpi=300)
ax = plt.gca() # gca: get current axis

# 调用plt.plot函数将两条曲线画在同一个坐标系内,并设置相关的参数
# 设置线条参数:设置颜色,线宽,线形,标记,标记大小,图例标签等等
plt.plot(X, Cos, color='blue', linewidth=1, linestyle='-', marker='>', ms=5, label='cosine')
plt.plot(X, Sin, color='red', linewidth=1, linestyle='--', marker='<', ms=5, label='sine')

# 设置图例(legend)
# plt.legend(loc='auto', frameon=False) # frameon is flag to draw a frame around the legend
# Advanced legend
plt.legend(bbox_to_anchor=(0.02, .95), loc=3, borderaxespad=0., frameon=False)

# 设置坐标轴的取值范围(lim)
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(-1.2, 1.2)

# 设置坐标轴的记号(ticks)
plt.xticks(np.linspace(-np.pi, np.pi, 5, endpoint=True), [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'], )

# 设置坐标轴的标签(label)
plt.xlabel('x_axis')
plt.ylabel('y_axis')

# # 打开grid选项
# plt.grid()

# 移动坐标轴到原点
# 先将上方和右方的spine去掉(color设为none即可)
# 再将x(y)坐标轴设为下方(左方)的spine,并且移动至原点
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))

# 标注(annotate)
# 在x=t处画虚线,并且把(t, y)这个用plt.scatter的方式标记出来
# 在(t, y)处用plt.annotate方法以箭头的方式做标注。
t = 2*np.pi/3

plt.plot([t,t], [0, np.cos(t)], color='blue', linewidth=1, linestyle='--')
plt.scatter([t], [np.cos(t)], 50, color='blue')
plt.annotate(r'$\cos(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
    xy=(t, np.cos(t)), xycoords='data',
    xytext=(-90, -30), textcoords='offset points', fontsize=11,
    arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))

plt.plot([t,t], [0, np.sin(t)], color='red', linewidth=1, linestyle='--')
plt.scatter([t], [np.sin(t)], 50, color='red')
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=11,
    arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))

# 标注(text)
plt.text(-2, 0.8, 'Annotation with pure text', verticalalignment='bottom', horizontalalignment='right', 
    color='green', fontsize=8, bbox={'facecolor':'red', 'alpha':0.4, 'pad':2})

# # 将figure保存在path
# fig_name = os.path.join(BASE_DIR, 'figure.jpg')
# fig.savefig(fig_name)
plt.show()

在这里插入图片描述

plot5

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值