日常科研绘图python绘图模板收集
棒棒糖图
from cProfile import label
from turtle import color
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#---------------------------------------------------------
def scatter1(cont):
#da1 = "m" + str(cont) + "-pro-ox" + ".dat"
#da2 = "m" + str(cont) + "-pro-oy" + ".dat"
da1 = "rho-mu-ix.dat"
picname = "rho-ix-" + str(cont) + ".png"
os.chdir(os.getcwd())# 确定用户执行路径
x0 = []
y0 = []
with open(da1) as file:
da = file.readlines()
for f1 in da:
if len(f1) > 3:
ldos = [float(x) for x in f1.strip().split()]
x0.append(ldos[0])
y0.append(ldos[cont]) # 这里是有多列数据才这样操作的
y0 = np.array(y0)
plt.figure(figsize=(8,8))
plt.bar(x0,y0,width=0.2,color='blue')
# plt.scatter(x0, y0, s = 20, color = 'blue', alpha = 0.7, linewidths = 0.3,label = "$p_y(i_x)$")
plt.scatter(x0, y0, s = 20, color = 'blue', linewidths = 0.3,label = "$p_y(i_x)$")
# plt.plot(x0, y0, c = 'blue', alpha = 0.5, markersize = 6,marker = 'o',label = "$p_y(i_x)$")
#plt.legend("x0")
x0min = np.min(x0)
x0max = np.max(x0)
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 30,
}
plt.xlim(x0min,x0max+1)
#plt.legend("x1")
# plt.ylim(-0.01,0.13)
plt.xlabel("$i_x$",font2)
plt.ylabel("$p_y(i_x)$",font2)
plt.legend(loc = 'upper right', ncol = 2, title = 'Edge polarization', shadow = True, fancybox = True, prop = font2,markerscale = 4)
plt.xticks([0,20,40],fontproperties='Times New Roman', size = 30)
plt.yticks([0,0.1],fontproperties='Times New Roman', size = 30)
plt.savefig(picname, dpi = 100, bbox_inches = 'tight')
plt.close()
#---------------------------------------------------------
def scatter2(cont):
#da1 = "m" + str(cont) + "-pro-ox" + ".dat"
#da2 = "m" + str(cont) + "-pro-oy" + ".dat"
da2 = "rho-mu-iy.dat"
picname = "rho-iy-" + str(cont) + ".png"
os.chdir(os.getcwd())# 确定用户执行路径
x0 = []
y0 = []
x1 = []
y1 = []
with open(da2) as file:
da = file.readlines()
for f1 in da:
if len(f1) > 3:
ldos = [float(x) for x in f1.strip().split()]
x1.append(ldos[0])
y1.append(ldos[cont])
y1 = np.array(y1)
plt.figure(figsize=(8,8))
# sc = plt.scatter(x0, y0, c = z1, s = 2,vmin = 0, vmax = 1, cmap="magma")
# plt.plot(x1, y1, c = 'red', alpha = 0.7, markersize = 6,marker = 'o',label = "$p_x(i_y)$")
plt.bar(x1,y1,width=0.2,color='red')
# plt.scatter(x1, y1, s = 20, color = 'red', alpha = 0.7, linewidths = 0.3,label = "$p_x(i_y)$")
plt.scatter(x1, y1, s = 20, color = 'red',linewidths = 0.3,label = "$p_x(i_y)$")
x0min = np.min(x1)
x0max = np.max(x1)
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 30,
}
plt.xlim(x0min,x0max+1)
#plt.legend("x1")
# plt.ylim(-0.01,0.13)
plt.xlabel("$i_y$",font2)
plt.ylabel("$p_x(i_y)$",font2)
plt.legend(loc = 'upper right', ncol = 2, title = 'Edge polarization', shadow = True, fancybox = True, prop = font2,markerscale = 4)
plt.xticks([0,20,40],fontproperties='Times New Roman', size = 30)
plt.yticks([0,0.1],fontproperties='Times New Roman', size = 30)
plt.savefig(picname, dpi = 100, bbox_inches = 'tight')
plt.close()
#---------------------------------------------------------
def main():
for i0 in range(1,50):
scatter1(i0)
scatter2(i0)
#---------------------------------------------------------
if __name__=="__main__":
main()
密度图(Python)
def density():
os.chdir(os.getcwd())# 确定用户执行路径
picname = "density.png"
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] # 这里步长是复数,表示以点数来进行分割
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
plt.figure(figsize=(12,12))
fig = plt.pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=np.min(Z),shading='nearest')
# fig = plt.pcolormesh(X, Y, Z, cmap='RdBu_r', vmin = -1, vmax = 1,shading='nearest')
cb = plt.colorbar(fig,fraction = 0.045,extend = 'both') # 调整colorbar的大小和图之间的间距
cb.ax.tick_params(labelsize=30) # corbar标签大小
cb.set_ticks(np.linspace(-1,1,2)) # color 刻度设置
cb.set_ticklabels(('-1','1.0'))
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 40,
}
cb.set_label('LDOS',fontdict = font2) #设置colorbar的标签字体及其大小
# plt.axis('scaled')
plt.yticks([0,1.5],fontproperties='Times New Roman', size = 30)
plt.xticks([0,1.5,3],fontproperties='Times New Roman', size = 30)
plt.savefig(picname, dpi=100,bbox_inches = 'tight')
plt.show()
y轴堆叠图
import matplotlib.pyplot as plt
import numpy as np
import os
from matplotlib import rcParams
config = {"font.size": 30,"mathtext.fontset":'stix',"font.serif": ['SimSun']}
rcParams.update(config) # Latex 字体设置
#-----------------------------------------------------
def plot1(cont):
# y轴平移堆叠图
# da1 = "ldos-" + str(cont).rjust(4,'0') + ".dat"
da1 = "h0-ldos-v2.dat"
picname = "ldos-" + str(cont).rjust(4,'0') + ".png"
os.chdir(os.getcwd())# 确定用户执行路径
x0 = np.linspace(-np.pi,np.pi,100)
plt.figure(figsize=(10,10))
for i0 in range(1,10):
lab = "(1," + str(i0) + ")"
plt.plot(x0,np.sin(i0*x0) + (i0 - 1)*2,label = lab,lw = 3.0)
x0min = np.min(x0)
x0max = np.max(x0)
font2 = {'family': 'Times New Roman','weight': 'normal','size': 30,}
font1 = {'family': 'Times New Roman','weight': 'normal','size': 20,}
# plt.xlim(x0min,x0max)
plt.xlim(x0min,x0max)
# plt.ylim(y0min,y0max + 1)
# plt.ylim(-0.5,0.5)
plt.xlabel(r'$E$',font2)
plt.ylabel("LDOS(E)",font2)
plt.yticks(fontproperties='Times New Roman', size = 30)
plt.xticks(fontproperties='Times New Roman', size = 30)
#plt.xticks([-1,-0.75,0,0.75,1],fontproperties='Times New Roman', size = 20)
#plt.yticks([-0.5,0,0.5],fontproperties='Times New Roman', size = 20)
#plt.vlines(x = 0.75, ymin = -1, ymax = 1,lw = 3.0, colors = 'blue', linestyles = '--')
#plt.vlines(x = -0.75, ymin = -1, ymax = 1,lw = 3.0, colors = 'blue', linestyles = '--')
wid = 0.1
x = [-wid,wid,wid,-wid]
y = [0,0,20,20]
plt.fill(x,y,c = "gray",alpha = 0.5) # 颜色填充
# plt.legend(prop = font2)
plt.legend(loc='upper right', shadow=True, fancybox=True,prop = font1)
ax1=plt.gca()
ax1.patch.set_facecolor("lightblue") # 设置 ax1 区域背景颜⾊
ax1.patch.set_alpha(0.3) # 设置 ax1 区域背景颜⾊透明度
plt.savefig(picname, dpi = 100, bbox_inches = 'tight')
plt.show()
#-------------------------------------------------------------------
plot1(1)
for i0 in range(1,10):
lab = "(1," + str(i0) + ")"
plt.plot(x0,np.sin(i0*x0) + (i0 - 1)*2,label = lab,lw = 3.0)
这里只需要把 (i0 - 1)*2
去掉就可以实现非堆叠的效果。
变色圆环
有时候想画一个随着角度变化的密度图,这里就给出一个例子,主要就是将matplotlib官网中的例子进行了修改
import matplotlib.tri as tri
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#---------------------------------------
def pltring():
n_angles = 100
n_radii = 8
min_radius = 0.7
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
z = (np.abs(np.sin(3 * angles))).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
# plt.figure(figsize=(12,12))
fig2, ax2 = plt.subplots(figsize=(10,10))
ax2.set_aspect('equal')
tpc = ax2.tripcolor(triang, z, shading='gouraud',cmap = "cividis_r")
cb = fig2.colorbar(tpc,fraction = 0.045)
cb.ax.tick_params(labelsize=20)
plt.yticks([-1,0,1],fontproperties='Times New Roman', size = 40)
plt.xticks([-1,0,1],fontproperties='Times New Roman', size = 40)
# plt.show()
picname = "phase-3.png"
plt.savefig(picname, dpi=100, bbox_inches = 'tight')
plt.close()
def pltring(cont):
n_angles = 1000
n_radii = 19
min_radius = 0.8
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
# z = (np.abs(np.sin(3 * angles))).flatten()
# z = ((np.cos(angles) +(-1)**cont * np.sin(angles)) * np.cos(2*angles)).flatten()
z = (np.cos(2*angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
# plt.figure(figsize=(12,12))
fig2, ax2 = plt.subplots(figsize=(10,10))
ax2.set_aspect('equal')
tpc = ax2.tripcolor(triang, z, shading='gouraud',cmap = "seismic")
cb = fig2.colorbar(tpc,fraction = 0.045,ticks=[-1, 0, 1],extend='both',label = r"$M(\alpha)$")
cb.ax.tick_params(labelsize = 20)
cb.ax.set_yticklabels([r'$<0$', r'$0$', r'$>0$'])
cb.ax.set_position([0.48, 0.3, 0.3, 0.4])
plt.yticks([],fontproperties='Times New Roman', size = 40)
plt.xticks([],fontproperties='Times New Roman', size = 40)
# plt.show()
ax = plt.gca()
ax.spines["bottom"].set_linewidth(0)
ax.spines["left"].set_linewidth(0)
ax.spines["right"].set_linewidth(0)
ax.spines["top"].set_linewidth(0)
picname = "mass-" + str(cont) + ".png"
plt.savefig(picname, dpi = 300, bbox_inches = 'tight',transparent = True)
plt.close()
高对称路径能带图
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
config = {
"font.size": 40,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#------------------------------------
def Pauli():
s0 = np.array([[1,0],[0,1]])
sx = np.array([[0,1],[1,0]])
sy = np.array([[0,-1j],[1j,0]])
sz = np.array([[1,0],[0,-1]])
return s0,sx,sy,sz
#-----------------------------------
def hamset(kx,ky,m0):
hn = 8
s0 = np.zeros([2,2],dtype = complex)
sx = np.zeros([2,2],dtype = complex)
sy = np.zeros([2,2],dtype = complex)
sz = np.zeros([2,2],dtype = complex)
ham = np.zeros([hn,hn],dtype = complex)
# m0 = 1.5
tx = 1.0
ty = 1.0
ax = 1.0
ay = 1.0
d0 = 0.0
dx = 0.5
dy = -dx
s0,sx,sy,sz = Pauli()
ham = (m0 - tx*np.cos(kx) - ty*np.cos(ky))*np.kron(np.kron(s0,sz),sz) + ax*np.sin(kx)*np.kron(np.kron(sz,sx),s0)\
+ ay*np.sin(ky)*np.kron(np.kron(s0,sy),sz) + (d0 + dx*np.cos(kx) + dy*np.cos(ky))*np.kron(np.kron(sy,s0),sy)
return ham
#------------------------------------------------------------------------------------
def engvals(kx,ky,m0):
# 求解本征值,python给出的是个复数,还不按照顺序排列,很烦
ham = hamset(kx,ky,m0)
vals = np.linalg.eigvals(ham)
# print(vals.real)
return sorted(vals.real)
#----------------------------------------------------------------------------------------------------
def HSP2(m0):
kxlist = np.linspace(0,np.pi,100)
relist1 = []
x0 = []
for kx in kxlist:
x0.append(kx/np.pi)
vals = engvals(kx,0,m0)
relist1.append(vals)
for ky in kxlist:
x0.append(ky/np.pi + 1)
vals = engvals(np.pi,ky,m0)
relist1.append(vals)
for k in kxlist:
x0.append(k/np.pi + 2)
vals = engvals(np.pi - k,np.pi - k,m0)
relist1.append(vals)
plt.figure(figsize=(8,8))
# plt.plot(x0,y01,c = "blue" ,lw = 4,label = r"$\tilde{M}^+_I\times \tilde{M}^+_{II}$")
# plt.plot(x0,y02,c = "red" ,lw = 4,label = r"$\tilde{M}^-_I\times \tilde{M}^-_{II}$")
plt.plot(x0,relist1,c = "blue" ,lw = 4)
# plt.plot(x0,y02,c = "red" ,lw = 4,label = r"$\tilde{M}^-$")
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 50,
}
x0min = np.min(x0)
x0max = np.max(x0)
y0max = np.max(relist1)
# plt.ylim(yaxmin,yaxman + 0.25)
# plt.text(pp1 - 0.2,-0.8,r"$0.23\pi$",color = "green")
# plt.text(pp2 ,-0.8,r"$0.27\pi$",color = "green")
plt.vlines(2,ymin = -y0max,ymax = y0max,lw = 2,colors = "black",ls = "--")
plt.vlines(1,ymin = -y0max,ymax = y0max,lw = 2,colors = "black",ls = "--")
plt.hlines(0,xmin = x0min,xmax = x0max,lw = 2,colors = "red",ls = "-.")
xtic = [0,1,2,3]
xticlab = ["$\Gamma$",r"$X$","$M$","$\Gamma$"]
plt.xticks(xtic,list(xticlab),fontproperties='Times New Roman', size = 40)
plt.yticks([-5,0,5],fontproperties='Times New Roman', size = 50)
plt.ylabel("$E/m_0$", font2)
plt.xlim(x0min,x0max)
plt.ylim(-y0max,y0max)
tit = "$m_0$ = " + str(m0)
plt.title(tit,font2)
# plt.legend(loc = 'upper right', ncol = 1, shadow = True, fancybox = True, prop = font1, markerscale = 0.5) # 图例
# ax1.patch.set_facecolor("lightblue") # 设置 ax1 区域背景颜⾊
# ax1.patch.set_alpha(0.5) # 设置 ax1 区域背景颜⾊透明度
# plt.show()
ax = plt.gca()
# ax.patch.set_facecolor("lightblue") # 设置 ax1 区域背景颜⾊
# ax.patch.set_alpha(0.5) # 设置 ax1 区域背景颜⾊透明度
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
picname = "hsp2-" + str(format(m0,".2f")) + ".png"
plt.savefig(picname, dpi = 100, bbox_inches = 'tight')
plt.close()
#----------------------------------------------------------------
if __name__=="__main__":
HSP2(1.)
# engvals(0.1,0.1,1)
密度图2
def ldosplt(cont):
dataname = "wave-30.00-Jx-" + str(cont) + ".dat"
# picname = "ldos-" + str(cont) + ".png"
picname = os.path.splitext(dataname)[0] + "-2" + ".png"
os.chdir(os.getcwd())# 确定用户执行路径
x0 = []
y0 = []
z0 = []
z1 = []
with open(dataname) as file:
da = file.readlines()
for f1 in da:
if len(f1) > 3:
ldos = [float(x) for x in f1.strip().split()]
x0.append(ldos[0])
y0.append(ldos[1])
z0.append(ldos[4] + ldos[5] + ldos[6] + ldos[7])
z0min = np.max(z0)
z0max = np.max(z0)
z0 = (z0 - np.min(z0))/(np.max(z0) - np.min(z0))*400 # 数据归一化
plt.figure(figsize=(8, 9))
# sc = plt.scatter(x0, y0, c = z0,s = z0,vmin = 0, vmax = z0max,cmap = "bwr",edgecolor = "black")
sc = plt.scatter(x0, y0, c = z0,s = 60,vmin = 0, vmax = z0max,cmap = "RdPu")
# sc = plt.scatter(x0, y0, c = z0,s = z0,vmin = 0, vmax = z0max,cmap="BuPu")
cb = plt.colorbar(sc,fraction = 0.1,ticks=[ 0, z0max],orientation='horizontal') # 调整colorbar的大小和图之间的间距
cb.ax.set_xticklabels(['Low', 'High'])
cb.ax.set_position([0.2, 0.2, 0.61, 0.1])
cb.ax.tick_params(labelsize=20)
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 40,
}
# cb.set_label('ldos',fontdict=font2) #设置colorbar的标签字体及其大小
# plt.scatter(x0, y0, s = 5, color='blue',edgecolor="blue")
plt.axis('scaled')
# plt.xlabel("x",font2)
# plt.ylabel("y",font2)
# tit = "$h_x= " + str(cont) + "$"
# plt.title(tit,font2)
plt.yticks([],fontproperties='Times New Roman', size = 40)
plt.xticks([],fontproperties='Times New Roman', size = 40)
plt.tick_params(axis='x',width = 0,length = 10)
plt.tick_params(axis='y',width = 0,length = 10)
ax = plt.gca()
ax.spines["bottom"].set_linewidth(0)
ax.spines["left"].set_linewidth(0)
ax.spines["right"].set_linewidth(0)
ax.spines["top"].set_linewidth(0)
plt.savefig(picname, dpi = 300,bbox_inches = 'tight')
plt.close()
线图+scatter
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import matplotlib.cm as cm
import os
import matplotlib.ticker as mticker
#----------------------------------------------------------
def lambda_singlet():
dataname = "singlet.dat"
picname = os.path.splitext(dataname)[0] + ".png"
da = np.loadtxt(dataname)
x0 = np.linspace(0.1,1,10)
plt.figure(figsize = (10,8))
plt.title("Singlet")
# labels = [r"$p_x$",r"$p_y$",r"$f_x$",r"$f_y$"]
labels = []
for i in range(len(da[1, :])):
labels.append(f"Curve {i+1}") # Create informative labels
for i0 in range(len(da[1, :])):
marker_style = ['o', 'p', 'D', '^', 's'][i0 % len(['o', 'p', 'D', '^', 's'])]
plt.plot(x0, da[:, i0], marker = marker_style, label = labels[i0],lw = 3, markersize = 10) # Use labels in plot and legend
# plt.plot(x0,da)
# marker_styles = ['o', 'p', 'D', '^', 's']
# for i0 in range(len(da[1,:])):
# marker_style = marker_styles[i0 % len(marker_styles)]
# # plt.scatter(x0,da[:,i0],s = 100,marker = marker_style)
# plt.scatter(x0,da[:,i0],s = 100)
font1 = {'family': 'Times New Roman','weight': 'normal','size': 20}
font2 = {'family': 'Times New Roman','weight': 'normal','size': 40}
plt.ylabel(r"$\lambda$",font2) # 调整标签到坐标轴距离
plt.xlabel(r"$U_0$",font2)
# Set X-Axis Precision
x_formatter = mticker.FormatStrFormatter(f"%.{2}f") # Set precision to 2 decimal places
x_locator = mticker.MaxNLocator(nbins=5) # Set number of ticks to 5
# Set Y-Axis Precision
y_formatter = mticker.FormatStrFormatter(f"%.{2}f") # Set precision to 3 significant digits
y_locator = mticker.AutoLocator() # Use automatic tick placement
plt.legend(loc='upper left', shadow=True, fancybox=True,prop = font1)
plt.tick_params(axis='x',width = 0,length = 10)
plt.tick_params(axis='y',width = 0,length = 10)
ax = plt.gca()
ax.xaxis.set_major_formatter(x_formatter)
ax.xaxis.set_major_locator(x_locator)
ax.yaxis.set_major_formatter(y_formatter)
ax.yaxis.set_major_locator(y_locator)
ax.spines["bottom"].set_linewidth(1)
ax.spines["left"].set_linewidth(1)
ax.spines["right"].set_linewidth(1)
ax.spines["top"].set_linewidth(1)
plt.savefig(picname, dpi = 300,bbox_inches = 'tight',transparent = True)
# plt.show()
plt.close()
自定义colorbar
def plotchi2(numk):
dataname = "chi-val-kn-" + str(format(numk,"0>3d")) + ".dat"
picname = os.path.splitext(dataname)[0] + ".png"
da = np.loadtxt(dataname)
x0 = da[:,0]
z0 = np.array(da[:,2])
xn = int(np.sqrt(len(x0)))
z0 = z0.reshape(xn,xn)
plt.figure(figsize = (10,10))
# Create custom colormap from Rainbow colormap
# Define colors
light = 0.7 # 控制颜色亮度 RGBA-->A alpha
colors1 = np.array([[0.163302, 0.12, 0.79,light], [0.25, 0.31, 0.89,light], [0.41, 0.54, 0.94,light],
[0.57, 0.73, 0.95,light], [0.72, 0.86, 0.93,light], [0.83, 0.90, 0.87,light],[0.85,0.85,0.85,light],
[0.89, 0.88, 0.77,light], [0.91, 0.79, 0.65,light], [0.87, 0.64, 0.52,light],
[0.80, 0.45, 0.39,light], [0.69, 0.24, 0.27,light], [0.53, 0.09, 0.17,light]])
cmap = colors.LinearSegmentedColormap.from_list('', colors1)
sc = plt.imshow(z0,interpolation='bilinear', cmap = cmap,origin='lower', extent=[-np.pi, np.pi, -np.pi, np.pi],vmax = z0.max(), vmin = z0.min())
# sc = plt.imshow(z0,interpolation='bilinear', cmap = "jet",origin='lower')
cb = plt.colorbar(sc,fraction = 0.045,extend = 'both',ticks = [np.min(z0),np.max(z0)]) # 调整colorbar的大小和图之间的间距
cb.ax.set_yticklabels([format(np.min(z0),".1f"),format(np.max(z0),".1f")])
cb.ax.tick_params(labelsize = 30) # 消除colorbar上的刻度
cb.set_label(r"$\chi^{(s)}$", labelpad = -25,loc = "center",size = 40)
# cb.ax.set_position([0.77, 0.2, 0.8, 0.6])
font2 = {'family': 'Times New Roman','weight': 'normal','size': 40}
plt.axis('scaled')
plt.xlabel(r"$q_x$",font2)
plt.ylabel(r"$q_y$",font2)
# tit = "$J_x= " + str(cont) + "$"
# plt.title(tit,font2)
xtic = [-np.pi,0,np.pi]
xticlab = ["$-\pi$","$0$","$\pi$"]
plt.xticks(xtic,list(xticlab),fontproperties='Times New Roman', size = 40)
plt.yticks(xtic,list(xticlab),fontproperties='Times New Roman', size = 40)
# plt.tick_params(axis='x',width = 2,length = 10)
# plt.tick_params(axis='y',width = 2,length = 10)
ax = plt.gca()
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# plt.show()
plt.savefig(picname, dpi = 300,bbox_inches = 'tight')
plt.close()
子图排列
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
import matplotlib.gridspec as gridspec
plt.rc('font', family='Times New Roman')
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#------------------------------------------------------------
def plotDs2(cont1):
dataname = "Ds_" + str(cont1) + ".dat"
picname = os.path.splitext(dataname)[0] + ".png"
da = np.loadtxt(dataname)
z0 = np.array(da)
# 创建一个 2x2 的子图布局
fig = plt.figure(figsize=(18, 16))
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 2]) # 上下行的高度比例
# 子图 1
ax1 = plt.subplot(gs[0, 0])
ax1.plot(z0[:,0], z0[:,1], lw=4, c="orange", label=r"$D^s_{xx}$")
ax1.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="red", ls="--")
# ax1.set_title(r"$D^s_{xx}$", fontsize = 30)
ax1.set_ylabel(r"$D^s$", fontsize=20)
ax1.set_xlabel(r"$U_0/t$", fontsize=30,labelpad = -25)
ax1.tick_params(axis='x', width=0, length=10)
ax1.tick_params(axis='y', width=0, length=10)
ax1.legend(loc='best', fontsize=25)
# 子图 2
ax2 = plt.subplot(gs[0, 1])
ax2.plot(z0[:,0], z0[:,4], lw=4, c="blue", label=r"$D^s_{yy}$")
ax2.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="red", ls="--")
# ax2.set_title(r"$D^s_{yy}$", fontsize = 30)
ax2.set_xlabel(r"$U_0/t$", fontsize=30,labelpad = -25)
ax2.tick_params(axis='x', width=0, length=10)
ax2.tick_params(axis='y', width=0, length=10)
ax2.legend(loc='best', fontsize=25)
# 子图 3
ax3 = plt.subplot(gs[1, 0]) # 这张子图跨越了底部整行
ax3.plot(z0[:,0], z0[:,1] + z0[:,4], lw=4, c="red", label=r"$D^s_{xx} + D^s_{yy}$")
ax3.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="red", ls="--")
# ax3.set_title(r"$D^s_{xx} + D^s_{yy}$", fontsize = 30)
ax3.set_xlabel(r"$U_0/t$", fontsize=30,labelpad = -25)
ax3.tick_params(axis='x', width=0, length=10)
ax3.tick_params(axis='y', width=0, length=10)
ax3.legend(loc='best', fontsize=25)
# 子图 3
ax3 = plt.subplot(gs[1, 1]) # 这张子图跨越了底部整行
ax3.plot(z0[:,0], z0[:,1], lw=4, c="orange", label=r"$D^s_{xx}$")
ax3.plot(z0[:,0], z0[:,4], lw=4, c="blue", label=r"$D^s_{yy}$")
ax3.plot(z0[:,0], z0[:,1] + z0[:,4], lw=4, c="red", label=r"$D^s_{xx} + D^s_{yy}$")
ax3.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="red", ls="--")
# ax3.set_title(r"$D^s_{xx} + D^s_{yy}$", fontsize = 30)
ax3.set_xlabel(r"$U_0/t$", fontsize=30,labelpad = -25)
ax3.tick_params(axis='x', width=0, length=10)
ax3.tick_params(axis='y', width=0, length=10)
ax3.legend(loc='best', fontsize=15)
# 设置整体标题和布局
fig.suptitle(r"Haldane model with filling(n) = $1/8$", fontsize=30)
plt.tight_layout(rect=[0, 0.1, 1, 1]) # 调整整体布局以避免标题重叠
# 保存并关闭图形
plt.savefig(picname, dpi=300, bbox_inches='tight')
plt.close()
曲线填充
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
import matplotlib.gridspec as gridspec
plt.rc('font', family='Times New Roman')
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#------------------------------------------------------------
def plotDs_filling(cont1):
dataname = "Ds_" + str(cont1) + ".dat"
picname = "filling" + os.path.splitext(dataname)[0] + ".png"
da = np.loadtxt(dataname)
z0 = np.array(da)
# 创建一个 2x2 的子图布局
fig = plt.figure(figsize=(18, 16))
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 2]) # 上下行的高度比例
# 子图 1
ax1 = plt.subplot(gs[0, 0])
ax1.plot(z0[:,0], z0[:,1], lw=4, c="orange", label=r"$D^{\rm geo}_{xx}$")
ax1.fill_between(z0[:,0], z0[:,1], color="orange", alpha=0.3)
if(cont1 == 1):
ax1.plot(z0[:,0], z0[:,5], lw=4, c="orange", label=r"$D^{\rm con}_{xx}$", ls="-.")
ax1.fill_between(z0[:,0], z0[:,5], color="orange", alpha=0.3)
ax1.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="black", ls="--")
ax1.set_ylabel(r"$D^s$", fontsize = 30)
ax1.set_xlabel(r"$U_0/t$", fontsize = 30, labelpad=-25)
ax1.tick_params(direction='in', axis = 'x', width=1, length=6)
ax1.tick_params(direction='in', axis = 'y', width=1, length=6)
ax1.legend(loc='best', fontsize=25)
# 子图 2
ax2 = plt.subplot(gs[0, 1])
ax2.plot(z0[:,0], z0[:,4], lw=4, c="blue", label=r"$D^{\rm geo}_{yy}$")
ax2.fill_between(z0[:,0], z0[:,4], color="blue", alpha=0.3)
if(cont1 == 1):
ax2.plot(z0[:,0], z0[:,8], lw=4, c="blue", label=r"$D^{\rm con}_{yy}$", ls="-.")
ax2.fill_between(z0[:,0], z0[:,8], color="blue", alpha=0.3)
ax2.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="black", ls="--")
ax2.set_xlabel(r"$U_0/t$", fontsize = 30, labelpad=-25)
ax2.tick_params(direction='in', axis = 'x', width=1, length=6)
ax2.tick_params(direction='in', axis = 'y', width=1, length=6)
ax2.legend(loc='best', fontsize=25)
# 子图 3
ax3 = plt.subplot(gs[1, 0]) # 这张子图跨越了底部整行
ax3.plot(z0[:,0], z0[:,1] + z0[:,4], lw=4, c="red", label=r"$D^{\rm geo}_{xx} + D^{\rm geo}_{yy}$")
ax3.fill_between(z0[:,0], z0[:,1] + z0[:,4], color="red", alpha=0.3)
if(cont1 == 1):
ax3.plot(z0[:,0], z0[:,4] + z0[:,8], lw=4, c="red", label=r"$D^{\rm con}_{xx} + D^{\rm con}_{yy}$", ls="-.")
ax3.fill_between(z0[:,0], z0[:,4] + z0[:,8], color="red", alpha=0.3)
ax3.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="black", ls="--")
ax3.set_xlabel(r"$U_0/t$", fontsize = 30, labelpad=-25)
ax3.tick_params(direction='in', axis = 'x', width=1, length=6)
ax3.tick_params(direction='in', axis = 'y', width=1, length=6)
ax3.legend(loc='best', fontsize=25)
# 子图 4
ax4 = plt.subplot(gs[1, 1]) # 这张子图跨越了底部整行
if(cont1 == 1):
ax4.plot(z0[:,0], z0[:,1] + z0[:,5], lw=4, c="orange", label=r"$D^s_{xx}$")
ax4.fill_between(z0[:,0], z0[:,1] + z0[:,5], color="orange", alpha=0.3)
ax4.plot(z0[:,0], z0[:,4] + z0[:,8], lw=4, c="blue", label=r"$D^s_{yy}$")
ax4.fill_between(z0[:,0], z0[:,4] + z0[:,8], color="blue", alpha=0.3)
ax4.plot(z0[:,0], z0[:,1] + z0[:,4] + z0[:,5] + z0[:,8], lw=4, c="red", label=r"$D^s_{xx} + D^s_{yy}$")
ax4.fill_between(z0[:,0], z0[:,1] + z0[:,4] + z0[:,5] + z0[:,8], color="red", alpha=0.3)
else:
ax4.plot(z0[:,0], z0[:,1], lw=4, c="orange", label=r"$D^s_{xx}$")
ax4.fill_between(z0[:,0], z0[:,1], color="orange", alpha=0.3)
ax4.plot(z0[:,0], z0[:,4], lw=4, c="blue", label=r"$D^s_{yy}$")
ax4.fill_between(z0[:,0], z0[:,4], color="blue", alpha=0.3)
ax4.plot(z0[:,0], z0[:,1] + z0[:,4], lw=4, c="red", label=r"$D^s_{xx} + D^s_{yy}$")
ax4.fill_between(z0[:,0], z0[:,1] + z0[:,4], color="red", alpha=0.3)
ax4.hlines(0, xmin=np.min(z0[:,0]), xmax=np.max(z0[:,0]), lw=3, colors="black", ls="--")
ax4.set_xlabel(r"$U_0/t$", fontsize = 30, labelpad=-25)
ax4.tick_params(direction='in', axis = 'x', width=1, length=6)
ax4.tick_params(direction='in', axis = 'y', width=1, length=6)
ax4.legend(loc='best', fontsize=25)
# 设置整体标题和布局
fig.suptitle(r"Haldane model with filling(n) = $15/8$", fontsize = 30)
plt.tight_layout(rect=[0, 0.1, 1, 1]) # 调整整体布局以避免标题重叠
# 保存并关闭图形
plt.savefig(picname, dpi = 300, bbox_inches='tight')
plt.close()
密度图3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
import matplotlib.gridspec as gridspec
from matplotlib.path import Path
plt.rc('font', family='Times New Roman')
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
def plotVscr():
# dataname = "chi-val-kn-" + str(format(numk,"0>3d")) + ".dat"
dataname = "Vscr.dat"
picname = os.path.splitext(dataname)[0] + "-1" + ".png"
da = np.loadtxt(dataname)
# 使用第一列和第二列分别作为 kx 和 ky
x0 = da[:, 0]
y0 = da[:, 1]
z0 = np.array(da[:, 2])
# 确定坐标范围
xmin, xmax = x0.min(), x0.max()
ymin, ymax = y0.min(), y0.max()
# 假设 kx, ky 网格是方形的,计算网格大小
xn = int(np.sqrt(len(x0)))
# 将 z0 重塑为二维矩阵
z0 = z0.reshape(xn, xn)
# 绘图
plt.figure(figsize=(10, 9))
# 将 extent 参数设置为 (xmin, xmax, ymin, ymax)
sc = plt.imshow(z0, interpolation='bilinear', cmap="seismic", origin='lower', extent=[xmin, xmax, ymin, ymax])
# 添加 colorbar
cb = plt.colorbar(sc, fraction=0.045)
cb.ax.tick_params(labelsize=20)
# 设置字体
font2 = {'family': 'Times New Roman', 'weight': 'normal', 'size': 40}
# 添加坐标轴标签
plt.xlabel(r"$k_x$", font2)
plt.ylabel(r"$k_y$", font2)
# 隐藏坐标轴刻度值
plt.yticks( fontproperties='Times New Roman', size=40)
plt.xticks( fontproperties='Times New Roman', size=40)
plt.tick_params(direction = 'in' ,axis = 'x',width = 0,length = 10)
plt.tick_params(direction = 'in' ,axis = 'y',width = 0,length = 10)
# 设置坐标轴的线条宽度
ax = plt.gca()
# 减少 x 和 y 轴上的刻度数量
ax.locator_params(axis='x', nbins = 3) # x 轴最多显示 3 个刻度
ax.locator_params(axis='y', nbins = 3) # y 轴最多显示 3 个刻度
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# 保存图像
plt.savefig(picname, dpi=100, bbox_inches='tight')
plt.close()
密度等高线图
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
import matplotlib.gridspec as gridspec
from matplotlib.path import Path
plt.rc('font', family='Times New Roman')
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
def plotVscr2():
# dataname = "chi-val-kn-" + str(format(numk,"0>3d")) + ".dat"
dataname = "Vscr.dat"
picname = os.path.splitext(dataname)[0] + "-2" + ".png"
da = np.loadtxt(dataname)
# 使用第一列和第二列分别作为 kx 和 ky
x0 = da[:, 0]
y0 = da[:, 1]
z0 = np.array(da[:, 2])
# 确定坐标范围
xmin, xmax = x0.min(), x0.max()
ymin, ymax = y0.min(), y0.max()
# 假设 kx, ky 网格是方形的,计算网格大小
xn = int(np.sqrt(len(x0)))
# 将 z0 重塑为二维矩阵
z0 = z0.reshape(xn, xn)
# 生成 kx 和 ky 的网格
kx = np.linspace(xmin, xmax, xn)
ky = np.linspace(ymin, ymax, xn)
KX, KY = np.meshgrid(kx, ky)
# 绘图
plt.figure(figsize=(10, 9))
# 绘制密度分布的等高线填充图
contour_filled = plt.contourf(KX, KY, z0, levels = 10, cmap = "seismic")
# 绘制等高线轮廓
contour_lines = plt.contour(KX, KY, z0, levels = 5, colors='black', linewidths = 1.5)
# 为等高线添加标签
# plt.clabel(contour_lines, inline = True, fontsize=15, fmt='%1.1f')
# 添加 colorbar 表示密度分布
cb = plt.colorbar(contour_filled, fraction = 0.045)
cb.ax.tick_params(labelsize=20)
#-------------------------------------------------
r0 = 0.1
hex = [np.sqrt(3)/2 * r0,np.sqrt(3)/4 * r0,-np.sqrt(3)/4 * r0,-np.sqrt(3)/2 * r0,-np.sqrt(3)/4 * r0,np.sqrt(3)/4 * r0,np.sqrt(3)/2 * r0]
hey = [0 * r0 ,3/4 * r0 ,3/4 * r0 ,0 * r0 ,-3/4 * r0 ,-3/4 * r0 ,0 * r0]
plt.plot(hex,hey,c = "cyan",lw = 4,ls = "-.")
#-------------------------------------------------
# 设置字体
font2 = {'family': 'Times New Roman', 'weight': 'normal', 'size': 40}
# 添加坐标轴标签
plt.xlabel(r"$k_x$", font2)
plt.ylabel(r"$k_y$", font2)
# 设置坐标轴刻度字体大小
plt.xticks(fontproperties='Times New Roman', size=40)
plt.yticks(fontproperties='Times New Roman', size=40)
plt.tick_params(direction = 'in' ,axis = 'x',width = 0,length = 10)
plt.tick_params(direction = 'in' ,axis = 'y',width = 0,length = 10)
# 设置坐标轴的线条宽度
ax = plt.gca()
ax.locator_params(axis='x', nbins = 3) # x 轴最多显示 3 个刻度
ax.locator_params(axis='y', nbins = 3) # y 轴最多显示 3 个刻度
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# 保存图像
plt.savefig(picname, dpi=300, bbox_inches='tight')
plt.close()
限制绘图区域
def plotVscr3():
# dataname = "chi-val-kn-" + str(format(numk,"0>3d")) + ".dat"
dataname = "Vscr.dat"
picname = os.path.splitext(dataname)[0] + "-3" + ".png"
da = np.loadtxt(dataname)
# 使用第一列和第二列分别作为 kx 和 ky
x0 = da[:, 0]
y0 = da[:, 1]
z0 = np.array(da[:, 2])
# 确定坐标范围
xmin, xmax = x0.min(), x0.max()
ymin, ymax = y0.min(), y0.max()
# 假设 kx, ky 网格是方形的,计算网格大小
xn = int(np.sqrt(len(x0)))
# 将 z0 重塑为二维矩阵
z0 = z0.reshape(xn, xn)
# 生成 kx 和 ky 的网格
kx = np.linspace(xmin, xmax, xn)
ky = np.linspace(ymin, ymax, xn)
KX, KY = np.meshgrid(kx, ky)
# 创建六角形布里渊区的顶点
r0 = 0.1
hex_x = [np.sqrt(3)/2 * r0, np.sqrt(3)/4 * r0, -np.sqrt(3)/4 * r0, -np.sqrt(3)/2 * r0, -np.sqrt(3)/4 * r0, np.sqrt(3)/4 * r0, np.sqrt(3)/2 * r0]
hex_y = [0 * r0 , 3/4 * r0 , 3/4 * r0 , 0 * r0 , -3/4 * r0 , -3/4 * r0 , 0 * r0]
# 创建 Path 对象,定义六角形区域
hexagon_path = Path(np.column_stack((hex_x, hex_y)))
# 使用 mask 将六角形区域外的数据屏蔽
points = np.column_stack((KX.flatten(), KY.flatten()))
mask = ~hexagon_path.contains_points(points) # 六角形外部的点被标记为 True
z0_masked = np.ma.masked_where(mask.reshape(xn, xn), z0) # 将外部点屏蔽
# 绘图
plt.figure(figsize=(10, 9))
# 绘制密度分布的等高线填充图(只在六角形区域内显示)
contour_filled = plt.contourf(KX, KY, z0_masked, levels = 30, cmap = "seismic") # bwr,seismic
# 绘制等高线轮廓(同样只在六角形区域内)
contour_lines = plt.contour(KX, KY, z0_masked, levels = 20, colors='black', linewidths=1.5)
# 添加 colorbar 表示密度分布
cb = plt.colorbar(contour_filled, fraction=0.045)
cb.ax.tick_params(labelsize=20)
# 绘制六角形边界
plt.plot(hex_x, hex_y, c="cyan", lw=4, ls="-.")
# 设置字体
font2 = {'family': 'Times New Roman', 'weight': 'normal', 'size': 40}
# 添加坐标轴标签
plt.xlabel(r"$k_x$", font2)
plt.ylabel(r"$k_y$", font2)
plt.xlim(-0.1,0.1)
plt.ylim(-0.1,0.1)
# 设置坐标轴刻度字体大小
plt.xticks(fontproperties='Times New Roman', size=40)
plt.yticks(fontproperties='Times New Roman', size=40)
plt.tick_params(direction='in', axis='x', width=0, length=10)
plt.tick_params(direction='in', axis='y', width=0, length=10)
# 设置坐标轴的线条宽度
ax = plt.gca()
ax.locator_params(axis='x', nbins=3) # x 轴最多显示 3 个刻度
ax.locator_params(axis='y', nbins=3) # y 轴最多显示 3 个刻度
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# 保存图像
plt.savefig(picname, dpi=300, bbox_inches='tight')
plt.close()
费米点+矢量箭头
数据生成代码
module code_param
implicit none
integer, parameter :: dp = kind(1.0)
real(dp),parameter::pi = acos(-1.0)
complex(dp),parameter::im = (0.,1.) ! Imagine unit
real(dp) delta_E
integer nkx,nky,ne
parameter(delta_E = 1e-4,nkx = 301,nky = 101,ne = 10)
end module code_param
!==============================================================================================================================================================
program main
use code_param
implicit none
call Gas_2D()
stop
end program main
!==============================================================================================================================================================
subroutine Gas_2D()
! 自由电子气测试
use code_param
implicit none
real(dp) t0,ek,kx,ky,mu
integer kn,ikx,iky,ik0
kn = 50
mu = 0.0
t0 = 1.0
open(30,file = "FS.dat")
open(31,file = "Arrow.dat")
do ikx = -kn,kn
do iky = -kn,kn
kx = pi * ikx/kn
ky = pi * iky/kn
ek = -t0 * (cos(kx) + cos(ky))
if(abs(ek - mu) .le. delta_E)then
write(30,"(20F15.8)")kx,ky,ek,sin(kx),sin(ky),sin(kx + ky),sqrt(sin(kx)**2 + sin(ky)**2)
end if
if(abs(ek - mu) .le. 1e-3 * delta_E)then
write(31,"(20F15.8)")kx,ky,ek,sin(kx),sin(ky),sin(kx + ky),sqrt(sin(kx)**2 + sin(ky)**2)
end if
end do
end do
close(30)
close(31)
end subroutine
绘图代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import os
import matplotlib.gridspec as gridspec
from matplotlib.path import Path
import matplotlib.colors as mcolors
plt.rc('font', family='Times New Roman')
config = {
"font.size": 30,
"mathtext.fontset":'stix',
"font.serif": ['SimSun'],
}
rcParams.update(config) # Latex 字体设置
#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def plotfs():
# 简单绘制个费米面
dataname = "FS.dat"
picname = os.path.splitext(dataname)[0] + ".png"
da = np.loadtxt(dataname)
plt.figure(figsize = (10,8))
# pair = da2[:,con1 - 1]
pair = da[:,4]
vmin, vmax = np.min(pair), np.max(pair)
norm = mcolors.TwoSlopeNorm(vmin = vmin, vcenter = 0, vmax = vmax)
sc = plt.scatter(da[:,0],da[:,1], c = da[:,4] ,s = 5, cmap = "seismic")
# sc = plt.scatter(da[:,0],da[:,1], c = da[:,3] ,s = 5, cmap = "seismic",norm = norm)
cb = plt.colorbar(sc,fraction = 0.1,ticks = [np.min(pair),0,np.max(pair)],extend='both',label = r"$\lambda$") # 调整colorbar的大小和图之间的间距
cb.ax.tick_params(size = 0)
cb.ax.set_yticklabels([format(np.min(pair),".1f"), format(0,".1f"),format(np.max(pair),".1f")])
valx = 0.5
valy = 0.5
plt.xlim(-valx,valx)
plt.ylim(-valy,valy)
plt.tick_params(direction = 'in' ,axis = 'x',width = 0,length = 10)
plt.tick_params(direction = 'in' ,axis = 'y',width = 0,length = 10)
# plt.axis('scaled')
ax = plt.gca()
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# plt.show()
plt.savefig(picname, dpi = 300,bbox_inches = 'tight')
plt.close()
#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def plotfs_2():
# 绘制有颜色的
da1 = "FS.dat"
da2 = "Arrow.dat"
# picname = os.path.splitext(da1)[0] + ".png"
picname = "Results.png"
da1 = np.loadtxt(da1)
da2 = np.loadtxt(da2)
plt.figure(figsize = (10,8))
# pair = da2[:,con1 - 1]
pair = da1[:,4]
vmin, vmax = np.min(pair), np.max(pair)
norm = mcolors.TwoSlopeNorm(vmin = vmin, vcenter = 0, vmax = vmax)
sc = plt.scatter(da1[:,0],da1[:,1], c = da1[:,4] ,s = 5, cmap = "seismic")
# sc = plt.scatter(da[:,0],da[:,1], c = da[:,3] ,s = 5, cmap = "seismic",norm = norm)
cb = plt.colorbar(sc,fraction = 0.1,ticks = [np.min(pair),0,np.max(pair)],extend='both',label = r"$\lambda$") # 调整colorbar的大小和图之间的间距
cb.ax.tick_params(size = 0)
cb.ax.set_yticklabels([format(np.min(pair),".1f"), format(0,".1f"),format(np.max(pair),".1f")])
#----------------
# 矢量起点坐标 (kx,ky)
x0 = np.array(da2[:,0])
y0 = np.array(da2[:,1])
# 矢量方向(v0,u0)
v0 = np.array(da2[:,2]) * 10 # 向量场方向
u0 = np.array(da2[:,3]) * 10
magnitude = da2[:,5] # 控制箭头颜色
# plt.quiver(x0, y0, v0, u0, color='b', angles='xy', scale_units='xy', scale=2)
sc = plt.quiver(x0, y0, v0, u0, magnitude, cmap = 'plasma', angles='xy', scale_units='xy', scale = 10)
# vmin, vmax = np.min(magnitude), np.max(magnitude)
# norm = mcolors.TwoSlopeNorm(vmin = vmin, vcenter = 0, vmax = vmax)
cb = plt.colorbar(sc,fraction = 0.1,ticks = [np.min(magnitude),0,np.max(magnitude)],extend='both',label = r"$s_z$") # 调整colorbar的大小和图之间的间距
cb.set_label(r"$s_z$", labelpad = -35) # 设置 labelpad 调整距离
cb.ax.tick_params(size = 0)
cb.ax.set_yticklabels([format(np.min(magnitude),".1f"), format(0,".1f"),format(np.max(magnitude),".1f")])
# plt.quiver(x0, y0, v0, u0, magnitude, cmap='seismic', scale = 5)
# xtic = [-np.pi,0,np.pi]
# xticlab = ["$-\pi$","$0$","$\pi$"]
# plt.xticks(xtic,list(xticlab),fontproperties='Times New Roman', size = 40)
# plt.yticks(xtic,list(xticlab),fontproperties='Times New Roman', size = 40)
# valx = 0.5
# valy = 0.5
# plt.xlim(-valx,valx)
# plt.ylim(-valy,valy)
plt.tick_params(direction = 'in' ,axis = 'x',width = 0,length = 10)
plt.tick_params(direction = 'in' ,axis = 'y',width = 0,length = 10)
# plt.axis('scaled')
ax = plt.gca()
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
# plt.show()
plt.savefig(picname, dpi = 300,bbox_inches = 'tight')
plt.close()
#------------------------------------------------------------
if __name__=="__main__":
# plotfs()
plotfs_2()
公众号
相关内容均会在公众号进行同步,若对该Blog感兴趣,欢迎关注微信公众号。