【问题标题】:How to display Pandas array with Cyrillic in Matplotlib如何在 Matplotlib 中使用 Cyrillic 显示 Pandas 数组
【发布时间】:2016-04-06 14:54:04
【问题描述】:

我正在构建一个工具,它使用 Pandas 读取 uft-8 编码的文本文件并在 Matplotlib 上显示该字段。将其视为用于训练目的的穷人遥测显示器。我遇到的问题是代码没有显示西里尔文的字段,但它能够显示 txt 文件中的其他字段。当字段被“硬编码”到图中时,该图确实显示了西里尔字母。

这是代码(你可能会看到我是这个东西的新手):

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt # Plotting library
import numpy as np # Numpy library for arrays
import matplotlib.cbook as cbook
import pandas as pd
from pylab import *
import matplotlib as mpl
from pylab import rcParams
import matplotlib.cm as cm
from pandas import set_option
set_option("display.max_rows", 10) #Allows to control how Pandas displays the result

# Set image size
rcParams['figure.figsize'] = 12, 10

# Read the rndz telemetry file with pandas
filename = "data.txt"
data = pd.read_table(filename, sep="\s+")

# 361 is the size of the txt file
for i in range(361):

    plt.clf() # Clears the screen

    plt.xlim(0.5,8) # Set the x-limits on the display
    plt.ylim(1,7) # Set the y-limits on the display

    plt.text(5.9,6.70,str(data.one[i])) # Adds regular text

    #This field is the one giving me trouble
    plt.text(5.9,6.40,str(data.two[i]) # Add cyrillic text

    #The field below is displayed properly on the plot 
    plt.text(1.25,6.7,u'заглавие', color="#ffffff", fontdict=font) # Add title

    xticks([]), yticks([]) # Erase the axes

    plt.show() # Render the plot
    plt.pause(1) # Wait before the next loop executes

如果我注释 data.two 字段的显示,代码运行良好。但是,当要求代码绘制该字段中的文本时,即西里尔文文本,这是我得到的:

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

我在 Windows 7 中运行 Enthough Canopy Python 2.7。有什么想法吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    通过将encoding= 参数传递给read_table 函数来读回您的utf8 编码文件:

    data = pd.read_table(filename, sep="\s+", encoding="utf-8")
    

    【讨论】:

    • 谢谢。这有帮助。我还找到了this thread,它帮助我在脚本中设置了默认编码
    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2016-08-28
    • 2017-07-30
    • 2015-06-16
    相关资源
    最近更新 更多