将 Unicode 文本与 seaborn 一起使用 [英] Use Unicode text with seaborn

查看:44
本文介绍了将 Unicode 文本与 seaborn 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Seaborn 中使用 Unicode 文本.(Python 2.7)

我可以使用 Unicode 文本作为带有 matplotlib 的图块.例如,

 将matplotlib.pyplot导入为plt从matplotlib.font_manager导入FontPropertiesfp = FontProperties(fname ='/usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf')文字=u'bădărău'plt.plot([1,2,3,2], 标签=文本)plt.legend(prop = fp)

如何将这种字体属性设置为seaborn?实际上,在以下示例中,我想使用Unicode文本作为批注:

导入 seaborn 为 sns将numpy导入为npsns.heatmap(np.array([[1,2,3]]),annot = np.array([['a','b','c']]),fmt ='')#想要使用ă而不是a

如果我使用ă,我得到以下错误

UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xc4:序号不在范围内 (128)

解决方案

Batchelder链接很容易理解,但是如果您当前使用自己的字符串而不是传递到代码中的字符串进行绘图,请尝试此操作.

我从系统上安装的字体中选择了字体:

从matplotlib中的

 导入font_managerfont_paths = font_manager.findSystemFonts()font_objects = font_manager.createFontList(font_paths)font_names = [font_objects中f的f.name]打印字体名称

来自另一个SO.

I want to use Unicode text with Seaborn. (Python 2.7)

I can use Unicode text as a tile with matplotlib. For example,

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fp = FontProperties(fname='/usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf')
text = u'bădărău'
plt.plot([1,2,3,2], label=text)
plt.legend(prop=fp) 

How to set this kind of font properties to seaborn? Actually, I want to use Unicode text as annotations in the following example:

import seaborn as sns
import numpy as np
sns.heatmap(np.array([[1,2,3]]), annot=np.array([['a', 'b', 'c']]), fmt='')
# want to use ă instead of a

If I use ă, I get the following error

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)

解决方案

The Batchelder link is good to know, but if you are currently making plots with your own strings, not ones passed into the code, try this. The matplotlib documentation explains how to use unicode literals in your source code:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import seaborn as sns
from matplotlib.pyplot import show
import numpy as np

sns.set(font="Meiryo")
sns.heatmap(np.array([[1,2,3]]), annot=np.array([['ë', 'bădărău', 'ê']]),fmt='')
show()

Result:

I picked the font out of the ones installed on my system:

from matplotlib import font_manager

font_paths = font_manager.findSystemFonts()
font_objects = font_manager.createFontList(font_paths)
font_names = [f.name for f in font_objects]
print font_names

from another SO.

这篇关于将 Unicode 文本与 seaborn 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆