ipython中matplotlib中文显示问题

ipython中matplotlib中文显示问题_第1张图片

作者:金良([email protected]) csdn博客: http://blog.csdn.net/u012176591

ipython中matplotlib中文显示问题_第2张图片

from matplotlib.font_manager import fontManager 
import matplotlib.pyplot as plt 
import os 
import os.path 

fig = plt.figure(figsize=(12,8)) 
ax = fig.add_subplot(111) 
#subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=None, hspace=None)
plt.subplots_adjust(0.04, 0.04, 0.99, 0.95, 0, 0) 
plt.xticks([]) 
plt.yticks([]) 
x, y = 0.05, 0.18 

#查看你系统中所有可用的中文字体
fonts = [font.name for font in fontManager.ttflist if os.path.exists(font.fname) and os.stat(font.fname).st_size>1e6] 
font = set(fonts) 
dy = (1.0-y)/(len(fonts)/4 + (len(fonts)%4!=0)) 
for font in fonts: 
    t = ax.text(x, y, font+":"+u"中文C", {'fontname':font, 'fontsize':14}, transform=ax.transAxes) 
    ax.text(x, y-dy/2, font, transform=ax.transAxes) 
    x += 0.25 
    if x >= 1.0: 
        y += dy 
        x = 0.05 
ax.set_xlabel(u'横坐标',{'fontname':'STKaiti'})
ax.set_ylabel(u'纵坐标',{'fontname':'STHupo','fontsize':20})
plt.show() 

查看fonts内容列表:

[‘KaiTi’,
‘Malgun Gothic’,
‘STXingkai’,
‘Microsoft YaHei’,
‘Microsoft JhengHei’,
‘STXinwei’,
‘Nirmala UI’,
‘FZYaoTi’,
‘STKaiti’,
‘DFKai-SB’,
‘YouYuan’,
‘STXihei’,
‘Microsoft YaHei’,
‘STKaiti’,
‘Adobe Kaiti Std’,
‘STLiti’,
‘FangSong’,
‘LiSu’,
‘STSong’,
‘Arial Unicode MS’,
‘STFangsong’,
‘STSong’,
‘Malgun Gothic’,
‘SimHei’,
‘STHupo’,
‘STFangsong’,
‘SimSun-ExtB’,
‘Microsoft JhengHei’,
‘Adobe Fangsong Std’,
‘STZhongsong’,
‘STXinwei’,
‘Gabriola’,
‘Nirmala UI’,
‘FZShuTi’,
‘Adobe Fangsong Std’,
‘FZYaoTi’,
‘STCaiyun’,
‘Adobe Kaiti Std’,
‘STZhongsong’,
‘Nirmala UI’,
‘Adobe Heiti Std’,
‘Adobe Song Std’,
‘STHupo’,
‘STCaiyun’,
‘STLiti’,
‘Nirmala UI’,
‘STXingkai’,
‘Arial Unicode MS’,
‘Adobe Heiti Std’,
‘Adobe Song Std’,
‘YouYuan’,
‘Gabriola’,
‘LiSu’,
‘STXihei’,
‘FZShuTi’]

即使不在ipython环境下,这种中文显示方式也是可用的。如

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import random

def mylogsig(mylist=range(-10,10),alpha=1.0):
    mylist = np.array(mylist)*alpha
    result = list(1.0/(1+np.exp(-mylist)))
    return result

mylambda = [1.5,0.5]
titles = [r'(a).$\lambda = 1.5$',r'(b).$\lambda = 0.5$']
num = 0

fig,axis = plt.subplots(nrows=2,ncols=1,figsize=(10,8))
fig.subplots_adjust(hspace=0.35)
x = range(-10,10)



for i in range(2):
    y = mylogsig(x,alpha=mylambda[num])
    axis[i].plot(x,y,'k-',linewidth=2)
    axis[i].plot(x,y,'bs')

    axis[i].set_xlabel(u'因变量n',{'fontname':'STFangsong','fontsize':18})
    axis[i].set_ylabel(u'函数值',{'fontname':'STFangsong','fontsize':18})
    axis[i].set_xticks(range(-10,11,1))
    axis[i].set_title(titles[num],fontsize=20)
    num += 1
    plt.savefig('mylogsig.png',dpi=400,bbox_inches='tight')

将其保存成 .py文件,双击运行。
ipython中matplotlib中文显示问题_第3张图片
注意第一行的# -*- coding: utf-8 -*- 一定不能缺,否则会乱码。

你可能感兴趣的:(matplotlib,ipython,中文显示问题)