Skip to main content
 首页 » 编程设计

python之如何在 Matplotlib 中显示带有西里尔字母的 Pandas 数组

2025年04月02日17duanxz

我正在构建一个使用 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。有什么问题吗?

请您参考如下方法:

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

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