尝试绘制迭代,但plt.plot为空 [英] try plotting an iteration but plt.plot is empty
问题描述
a = frame_query("select ....",db)
使用我的代码,变量'c'是我要绘制的numpy.ndarray.但是,当我执行以下代码时,我得到了一个空图!
With my code, the var 'c' is a numpy.ndarray which I would like to plot. However when I execute the following code, i get an empty plot!
for i in a.values:
c = (i[:1]-a.values[-1:])/a.values[-1:]*100
plt.plot(c)
plt.show()
print c
给予:
[[ 28.57142857]]
[[ 27.27272727]]
[[ 27.92207792]]
[[ 28.57142857]]
[[ 22.07792208]]
[[ 22.07792208]]
[[ 22.07792208]]
我到底哪里出问题了?
谢谢.
推荐答案
适应代码的最简单方法可能是在循环之前启动一个空列表,将c
中的值附加到循环中,然后绘图它在循环之后.例如:
The simplest way to adapt your code is probably to start an empty list before the loop, append the values from c
onto it within the loop and then plot it after the loop. For example:
c_series = []
for i in a.values:
c = (i[:1]-a.values[-1:])/a.values[-1:]*100
c_series.append(c[0])
plt.plot(c)
plt.show()
在这里使用c[0]
的
注意 是安全的,因为上面一行的逻辑保证ndarray
仅具有一个成员.
Note using c[0]
is safe here, because the logic of the line above guarantees that the ndarray
will only have one member.
但是 ,这是处理数据结构的一种奇怪方法.似乎a.values
是ndarray
,您也可以通过使用numpy提供的对数组执行算术运算的功能来完成此操作(由于我没有您的逐字记录,因此我无法对其进行测试a.values
):
However, that's a bit of an odd way to deal with your data structure. As it seems that a.values
is an ndarray
, you could also simply do this by using the facilities that numpy provides to perform arithmetical operations on arrays (I can't test it as I don't have a verbatim copy of your a.values
):
const = a.values[-1:]
c_series = (a.values - const) / const*100
plt.plot(c_series)
plt.show()
通常-使用numpy数组时,通常最好将它们保留为数组(称为向量化代码),而不是逐个循环地逐个处理它们.
In general - when using numpy arrays, it's often better to keep them as arrays (called vectorising the code), rather than dealing with them element by element in a loop.
这篇关于尝试绘制迭代,但plt.plot为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!