centos 之 Matplotlib不显示Times New Roman


前言

在centos下用python做科学论文图的时候需要用到Times New Roman字体,可是…… centos下并没有这个字体,运行下面代码

import matplotlib.pyplot as plt
plt.rc('font',family='Times New Roman')

出现错误信息

UserWarning: findfont: Font family [u'Times New Roman'] not found. Falling back to DejaVu Sans   (prop.get_family(), self.defaultFamily[fontext]))

安装

  • 把本地电脑里C:\windows\fonts中的Time New Roman文件夹/4个文件拷贝到CentOS系统中的/usr/share/fonts目录下。

    1. times.ttf
    2. timesbd.ttf
    3. timesbi.ttf
    4. timesi.ttf
  • root下执行如下命令

mkfontscale
mkfontdir
fc-cache -fv
  • 切换个人用户,删除matplotlib缓存
rm ~/.cache/matplotlib -rf

测试

import numpy as np
import matplotlib.pyplot as plt
from monty.serialization import loadfn
import string
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.ticker import FormatStrFormatter
from PIL import Image
from matplotlib.gridspec import GridSpec

def float_range(start,stop,step):
      return [start+i*step for i in range(int((stop-start)//step))]

#fig = plt.figure()
font = {'family': 'Times New Roman', 'size': 14, 'weight':'bold'}
plt.rc('font', **font)

cm = plt.cm.get_cmap('RdYlBu')
               #  C  N    E
NES=np.array([[ 12, 6, -156.36123303,60.1242],
 [     3 , 4  ,-58.74306942,19.8460],
 [     2 , 4 , -48.08202932,10.9879]])

C=NES[:,0];
print(C)
N=NES[:,1];
print(N)
En=NES[:,2];
S=NES[:,3];
print('En=')
print(En)
print('S=')
print(S)

grap=-9.22704312
nitro=-8.31684201
step=0.005
un=np.array(float_range(nitro,-4.3,step))
uc=np.array(float_range(grap-1,-7.3,step))


#change phosphorus potentail
color=['r','g','b','c','m','y','k'];

fig = plt.figure(figsize=(18,5))
gs = GridSpec(1, 3, width_ratios=[1,1,1],  wspace=0.32)#, hspace=0.2)
ax1 = plt.subplot(gs[0,0])

for k in range(len(N)):
   dE=(En[k]-C[k]*grap-N[k]*un)/(S[k]);
   ax1.plot(un,dE,c=color[k],lw=2)

lg=[r'$C_2N$',r'g-$C_3N_4$',r'penta-$CN_2$']
font = {'family': 'Times New Roman', 'size': 14}
ax1.legend(lg,prop=font)
#ax1.set_title('Stability of C_mN_n under different nitrogen chemical potential')
ax1.set_xlabel(r'$\mu_{N}$(eV)')
ax1.set_ylabel(r'Gribbs Free Energy (eV/$\AA$)')

ax2 = plt.subplot(gs[0,1])
for k in range(len(C)):
   dE=(En[k]-C[k]*uc-N[k]*nitro)/(S[k]);
   ax2.plot(uc,dE,c=color[k],lw=2)
#
ax2.legend(lg,prop=font) #,fontsize=16)
#ax2.set_title('Stability of C_mN_n under different carbon chemical potential')
ax2.set_xlabel(r'$\mu_{C}$(eV)')
ax2.set_ylabel(r'Gibbs Free Energy (eV/$\AA$)')
#%upc=meshgrid(up,uc);
ChemPot=np.zeros((len(un)*len(uc),2));
print(ChemPot.shape)
count=0;
print(len(un))
print(len(uc))
for m in range(len(un)):
     for n in range(len(uc)):
       ChemPot[count,:]=[un[m],uc[n]];
       count=count+1;
print(count)
#icount=0;
print(C.shape)
print(N.shape)
print(En.shape)
#CPEn=[C,N,En];
#disp(CPEn);
my=np.zeros((469755,3));
icount=0
for s in range(count):
   k=0;
   dE1=(En[k]-C[k]*ChemPot[s,1]-N[k]*ChemPot[s,0])/(S[k]);
   k=1;
   dE2=(En[k]-C[k]*ChemPot[s,1]-N[k]*ChemPot[s,0])/(S[k]);
   k=2;
   dE3=(En[k]-C[k]*ChemPot[s,1]-N[k]*ChemPot[s,0])/(S[k]);
    
   if ( ( dE3 <= dE1) and ( dE3 <= dE2) and (dE3 <= dE1)) :
      my[icount,:]=[ChemPot[s,0],ChemPot[s,1],dE3];
      icount=icount+1;
ax3 = plt.subplot(gs[0,2])
my=my[0:icount,:];
#icount
#figure()
skip=10
sc=ax3.scatter(my[:,0][0::skip],my[:,1][0::skip],c= my[:,2][0::skip],cmap=cm,marker='.')
ax3.set_xlabel(r'$\mu_{N}$(eV)');
ax3.set_ylabel(r'$\mu_{C}$(eV)')
ax3.set_xlim([-7.7,-4.0])
ax3.set_ylim([-10.5,-7.0])
ax3.set_yticks(float_range(-10.5,-6.5,0.5))
ax3.set_xticks(float_range(-7.5,-3.0,1.5))
plt.colorbar(sc)

yloc=-0.15
xloc=0.22
#ax1.text(xloc, yloc, '('+string.ascii_lowercase[0]+')', transform=ax1.transAxes,size=20, weight='bold')
#ax2.text(xloc, yloc, '('+string.ascii_lowercase[1]+')', transform=ax2.transAxes,size=20, weight='bold')
#ax3.text(xloc, yloc, '('+string.ascii_lowercase[2]+')', transform=ax3.transAxes,size=20, weight='bold')

ax3.scatter(-7.22,-7.78,s=60,marker='*',c='r')
plt.tight_layout()
plt.subplots_adjust(bottom=0.15)
plt.show()

#plt.savefig('FigS2N.jpg',format='jpg',dpi=300)
#plt.savefig('FigS2N.pdf',format='pdf',dpi=300)

penta-CN2

参考


文章作者: ustc-haidi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ustc-haidi !
  目录