Eastsheng's Wiki

Matplotlib基本-1

2021-01-22 18:11:28

[toc]

Matplotlib 中文

调整ylabel位置: labelpad

1
ax.set_ylabel("Interaction energy (kcal/mol)",fontweight='bold',size=28,labelpad=20)

修改边框宽度

1
2
3
4
5
bwith = 1.2
ax0.spines['bottom'].set_linewidth(bwith)
ax0.spines['left'].set_linewidth(bwith)
ax0.spines['top'].set_linewidth(bwith)
ax0.spines['right'].set_linewidth(bwith)

刻度朝内

1
2
3
# 此带代码应放在plt.plot()之前,才能生效
plt.rcParams['xtick.direction'] = 'in'#将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in'#将y轴的刻度方向设置向内

画自定义颜色曲线

Figure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
z = np.cos(x)#上色数据

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots(figsize=(5,3))
fig.subplots_adjust(bottom=0.1,left=0.2)##调整边界

norm = plt.Normalize(min(z),max(z))
lc = LineCollection(segments,cmap='jet',norm=norm)
lc.set_array(z)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line)

plt.xlim(0,2*np.pi)
plt.ylim(-1,1)
plt.savefig('fig1.png')
plt.show()

直方图

1
2
3
4
5
6
7
8
9
10
11
import numpy as np 
import matplotlib.pyplot as plt
X = np.linspace(0,1,10)
Y = np.ones(X.size)
plt.rc('font', family='Times New Roman',size=26)
fig, ax = plt.subplots(figsize=(10, 4))
fig.subplots_adjust(bottom=0.2,left=0.2)
ax.bar(X,Y,0.05,hatch='\\\\',color='white',edgecolor='c')
ax.set_xlabel('Eigenvector Amplitude',fontsize=26,fontweight='bold')
ax.set_ylabel('Count',fontsize=26,fontweight='bold')
plt.show()

直方截断图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np 
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes

X = np.linspace(0,1,10)
Y = np.ones(X.size)
plt.rc('font', family='Times New Roman',size=26)
# fig = plt.subplots(figsize=(10, 4))
fig = plt.figure(figsize=(10,4))
ax = brokenaxes(ylims=((0,0.5),(0.6,1)),hspace=0.06,despine=False)
# fig.subplots_adjust(bottom=0.2,left=0.2)
ax.bar(X,Y,0.05,hatch='\\\\',color='white',edgecolor='c')
# ax.set_xlabel('Eigenvector Amplitude',fontsize=26,fontweight='bold')
# ax.set_ylabel('Count',fontsize=26,fontweight='bold')
plt.show()

直方Log图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np 
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes

X = np.linspace(0,1,10)
Y = np.ones(X.size)
plt.rc('font', family='Times New Roman',size=26)
fig, ax= plt.subplots(figsize=(10, 4))
# fig = plt.figure(figsize=(10,4))
# ax = brokenaxes(ylims=((0,0.5),(0.6,1)),hspace=0.06,despine=False)
fig.subplots_adjust(bottom=0.2,left=0.2)
ax.bar(X,Y,0.05,hatch='\\\\',color='white',edgecolor='c')
ax.set_xlabel('Eigenvector Amplitude',fontsize=26,fontweight='bold')
ax.set_ylabel('Count',fontsize=26,fontweight='bold')
'''x、y坐标log'''
# ax.set_xscale("log")
ax.set_yscale("log")
plt.show()

点线图(Error Bar)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np 
import matplotlib.pyplot as plt

def plt_tc(tcfile):
tc = np.loadtxt(tcfile)
# print(tc)
x = tc[:,0]/32.06
y = tc[:,1:4]
y_mean = np.mean(y,axis=1)
y_std = np.std(y,axis=1)
# print(y_mean,y_std)
plt.rc('font',family='Times New Roman',size=26)
fig, ax = plt.subplots(figsize=(8,6))
fig.subplots_adjust(bottom=0.2,left=0.2)
s1 = ax.errorbar(x,y_mean,yerr=y_std,capsize=10,capthick=4,
fmt='bo:',mfc='w',mec='b',markersize=16,mew=2)
ax.legend(handles=[s1],labels=['$\mathregular{MoS_2}$/$\mathregular{MoSe^{78}}_\mathregular{2}$']
,loc='best', fontsize=26)
ax.set_xlabel('Mass ratio (R)',fontsize=26,fontweight='bold')
ax.set_ylabel('Thermal conductivity (W/m-K)',fontsize=26,fontweight='bold')
ax.set_xticks([0,1,2,3,4,5,6])
plt.show()
return

if __name__ == '__main__':
tcfile = './Thermal_conductivity.txt'
plt_tc(tcfile)

  • 数据
1
2
3
4
5
6
7
8.9    17.925 16.9828 16.4475
15.999 19.5132 18.2719 19.3751
32.06 25.3194 23.8796 25.2429
48.9 23.6784 21.4915 22.9888
78.9 15.9254 14.4494 15.1808
127.6 8.5564 9.0751 8.8317
209 5.2363 6.8541 5.3407

去掉坐标轴

1
2
3
plt.xticks([])  #去掉x轴
plt.yticks([]) #去掉y轴
plt.axis('off') #去掉坐标轴

or

1
2
3
4
5
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)

or

1
2
3
ax.set_xticks([]), ax_set_yticks([]) #关闭坐标刻度
ax.axis('off') #关闭坐标轴
ax.set_title()#设置标题

参考:
[1] https://blog.csdn.net/lly1122334/article/details/90647962
[2] https://blog.csdn.net/lanchunhui/article/details/80100430

调整图间距

1
2
3
fig.tight_layout()#调整整体处于正确位置
fig.subplots_adjust(bottom=0.2,left=0.15)#调整图间距
plt.subplots_adjust(wspace =0, hspace =0)#调整子图间距

参考:[1] https://blog.csdn.net/GAN_player/article/details/78543643

图片上添加文字

1
2
3
4
5
6

plt.text(x, y, string, #(x坐标,y坐标,'text')
fontsize=15,
verticalalignment="top",
horizontalalignment="right")
plt.text(100, 100, 'text') #example

Maplotlib坐标轴反转

1
2
ax.invert_xaxis()
ax.invert_yaxis()

python matplotlib 下标的字体设置问题

1
2
3
4
5
plt.rc('font', family='Times New Roman', size=18)
fig = plt.figure(figsize=(12,6))
fig.subplots_adjust(bottom=0.2,left=0.2,hspace=0.3)
ax=fig.add_subplot(111)
ax.set_ylabel(r'$\regular{gr_{OO}}(r)$',fontweight='bold',size=22)

图中图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset

# 创建数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 创建父图
fig, ax = plt.subplots()

# 绘制父图
ax.plot(x, y, label='sin(x)')

# 创建放大的子图
axins = zoomed_inset_axes(ax,2, loc='lower right')
mark_inset(ax, axins, loc1=2, loc2=1, linestyle="--", fc="none", ec="r")
# 绘制放大的子图
axins.plot(x, y, label='sin(x)')

# 设置放大子图的范围
axins.set_xlim(1, 3)
axins.set_ylim(0.5, 1)

# 将放大的子图绘制到父图上
ax.indicate_inset_zoom(axins)
fig.tight_layout()
# 显示图像
plt.show()