Anaconda+5.0.0+JupyterLab+0.27.0+中matplotlib显示中文标签

来源:互联网 发布:程序设计用什么软件 编辑:程序博客网 时间:2024/05/16 09:55

Anaconda 5.0.0 JupyterLab 0.27.0 中 matplotlib 显示中文标签

安全的安装Anaconda3 5.0.0 Windows x86_64

http://blog.csdn.net/hu_zhenghui/article/details/78154684

Anaconda 5.0.0 JupyterLab 0.27.0 中 matplotlib 显示中文标签

使用 matplotlib 绘制数据图的时候可能会涉及到本地化显示,例如导入 locale 包

import locale

为了绘制数据图,导入 matplotlib.pyplot 包

import matplotlib.pyplot

本例中以日期为例,导入 datetime 包

import datetime

为了以本地格式显示日期,设置地区,此处并未具体制定地区,而是使用 locale.LC_ALL ,从返回值可以看到是简体中文

locale.setlocale(locale.LC_ALL, '')
'Chinese (Simplified)_China.936'

演示数据

data = range(-7,7)

演示数据的标签

label = [(datetime.datetime.now() + datetime.timedelta(days=i)).strftime('%A') for i in data]

创建一个数据图

figure1 = matplotlib.pyplot.figure(figsize=(10,10))

添加一个坐标轴

axes1 = figure1.add_subplot(1,1,1)

使用演示数据和演示标签绘制柱状图

axes1.bar(data, data, tick_label=label)
<Container object of 14 artists>

保存数据图

figure1.savefig('1.png')

可以看到标签都显示成了空白方块

未显示中文

为了正确显示中文,需要替换数据图绘制时所使用的字体

matplotlib.pyplot.rcParams['font.sans-serif']=['SimHei']

创建第二个数据图

figure2 = matplotlib.pyplot.figure(figsize=(10,10))

为第二个数据图添加坐标轴

axes2 = figure2.add_subplot(1,1,1)

使用演示数据和演示标签绘制柱状图

axes2.bar(data, data, tick_label=label)
<Container object of 14 artists>

保存数据图

figure2.savefig('2.png')

可以看到数据标签显示正常了,但是负数的数据前面又出现了空白方块。

未显示负号

为此需要设置坐标轴中不使用 unicode 显示-减号

matplotlib.pyplot.rcParams['axes.unicode_minus']=False 

创建第三个数据图

figure3 = matplotlib.pyplot.figure(figsize=(10,10))

为第三个数据图添加坐标轴

axes3 = figure3.add_subplot(1,1,1)

使用演示数据和演示标签绘制柱状图

axes3.bar(data, data, tick_label=label)
<Container object of 14 artists>

保存数据图

figure3.savefig('3.png')

可以看到数据标签和数据都正常了

正确显示中文和负号

原创粉丝点击