您的位置:首页 > 编程语言 > Python开发

解决python中matplotlib绘图中文显示问题

2014-03-23 14:09 1391 查看
matplotlib是支持unicode编码的,出现图1的问题主要是没有找到合适的中文字体,解决方法有两个:

1.直接修改配置文件matplotlibrc

这种方法我没有试过,因为我安装的是python(x,y),配置文件放的地方不一定一致,所以就选择了下面的方法

2.在代码中动态设置(推荐方式)

这种方式不需要修改配置文件,比较方便,推荐该方法,下面是具体步骤:

首先要再python脚本中的开头加上后面的内容:#-*- coding: utf-8 -*-,即用utf8编码

然后在代码中动态设置字体,下面是主要的几行代码

from matplotlib.font_manager import FontProperties

import matplotlib.pyplot as plt

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)

plt.xlabel(u"电压差(V)", fontproperties=font)

plt.ylabel(u"介质损耗角差(度)", fontproperties=font)

plt.title(u"介质损耗角和荷电状态SOC关系图",fontproperties=font)

下面举个具体的例子,因为我在网上看了很多例子,都解决不了这个问题,为了方便大家,下面贴出代码,需要的话可以直接贴过去运行:

#-*- coding: utf-8 -*-

from matplotlib.font_manager import FontProperties

import matplotlib.pyplot as plt

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)

plt.figure(figsize=(6,6))

x = [1,2,3,4,5,6,7,8]

y = []

for i in x:

y.append(-(i*i)+i+3)

plt.plot(x, y)

plt.title(u'测试程序', fontproperties=font)

plt.xlabel(u'x轴', fontproperties=font)

plt.ylabel(u'y轴', fontproperties=font)

plt.grid(True)

plt.show()

下面是程序的输出



文章转载:http://blog.chinaunix.net/uid-26611383-id-3521248.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: