尝试绘制数组时出现Unicode错误?

时间:2018-04-25 06:36:39

标签: python python-2.7 matplotlib 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的长度相同)。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:1)

python 2没有utf-8作为默认编码。使用

之一定义编码
# coding=utf-8
# -*- coding: utf-8 -*-

应该这样做。请参阅PEP-0263

然后您需要在标签前添加'u'

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