首页 > 解决方案 > 尝试绘制数组时出现 Unicode 错误?

问题描述

我有一个非常简单的代码,并试图将生成的 numpy 数组绘制pos为 的函数t,但我得到一个随机的 unicode 错误。我以前从未出现过这个错误,我不知道它的含义或它为什么会出现在这段代码中:

import numpy as np
import matplotlib.pyplot as plt

h = 0.5
x_0 = 1
w = 1
t = np.arange(0, 20, h)
pos, v = np.zeros(len(t)), np.zeros(len(t))
pos[0], v[0] = x_0, 0

def a(pos):
    return -w**2 * pos

for i in range(1, len(t)):
    # Stormer-Verlet method
    pos[i] = pos[i-1] + h*(v[i-1] + 0.5*h*a(pos[i-1]))
    v[i] = v[i-1] + 0.5*h*a(pos[i-1]) + 0.5*h*a(pos[i])

# Plotting position as a function of time
plt.plot(t, pos, label='Störmer-Verlet approximation')

在线plt.plot时,我收到此错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128). 我还打印pos并确认它是一个预期的数组,长度为 100(与 相同的长度t)。有谁知道为什么会这样?

标签: pythonpython-2.7matplotlibunicode

解决方案


python 2 没有 utf-8 作为默认编码。使用任何一个定义您的编码

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

应该做。请参阅PEP-0263

那么你需要在你的标签前加上一个'u'

plt.plot(t, pos, label=u'Störmer-Verlet approximation')

推荐阅读