循环遍历列表以使用matplotlib绘制

时间:2017-01-09 20:05:54

标签: python matplotlib

尝试使用包含年份和值的列表列表创建简单图表:

test_file = [[2000, 3.8], [2001, -2.4], [2002, 5.8], [2003, -10.5],
             [2004, 2.1], [2005, 2.1], [2006, 6.9], [2007, -3.9]]

for i in test_file:
    plot(test_file[i][0], test_file[i][1], marker="o",
         color="blue", markeredgecolor="black")
    axis([2000, 2007, -12, 10])
    show()

但我收到此错误:TypeError:list indices必须是整数或切片,而不是list

感谢。

3 个答案:

答案 0 :(得分:1)

如果您不介意导入numpy,将列表转换为数组非常轻松:

import numpy as np
import matplotlib.pyplot as plt

test_file = [[2000, 3.8], [2001, -2.4], [2002, 5.8], [2003, -10.5], [2004, 2.1], [2005, 2.1], [2006, 6.9], [2007, -3.9]]
test_file = np.array(test_file)

plt.plot(test_file[:, 0], test_file[:, 1])
plt.show()

答案 1 :(得分:0)

如果你写for i in test_file会发生什么是python迭代数组test_file并在第一次迭代中获取第一项[2000, 3.8]并为此分配i。这不是你想要的。您应该将代码更改为以下内容:

from matplotlib.pyplot import plot, axis, show

test_file = [[2000, 3.8], [2001, -2.4], [2002, 5.8], [2003, -10.5], [2004, 2.1], [2005, 2.1], [2006, 6.9], [2007, -3.9]]
for year, value in test_file:
    plot(year, value, marker="o", color="blue", markeredgecolor="black")

axis([2000, 2007, -12, 10])
show()
  

没有连接点的线

在这种情况下,您需要稍微改革一下数据:

dates = [i[0] for i in test_file]
values = [i[1] for i in test_file]
plot(dates, values, '-o', color="blue", markeredgecolor="black")
  

x轴是1-7对比2000 - 2007

是的,这有点奇怪。修复此问题的一种方法是将现在存储为整数的年份转换为python datetime.date并在其上运行autofmt_xdate(),因此整个代码为:

from matplotlib.pyplot import plot_date, axis, show, gcf
import datetime

test_file = [[2000, 3.8], [2001, -2.4], [2002, 5.8], [2003, -10.5], [2004, 2.1], [2005, 2.1], [2006, 6.9], [2007, -3.9]]

dates = [datetime.date(i[0], 1, 1) for i in test_file]
values = [i[1] for i in test_file]
plot_date(dates, values, "-o", color="blue", markeredgecolor="black")
gcf().autofmt_xdate()
show()

答案 2 :(得分:0)

对于线连接点,您需要在列表中一起指定绘图数据,如下所示。

奖励:我在function zoomIn() { try { var $fotoramaDiv = $('#fotorama').fotorama(); var fotorama = $fotoramaDiv.data('fotorama'); var $frame = fotorama.activeFrame.$stageFrame; //the following line does not work $frame.childNode.height=500; } catch (error) { alert(error.Message); } } 中的数据发生变化时,将x,y低值和高值添加为变量而不是硬编码。

修改
已将test_file添加到ScalerFormatter的代码中以显示实际的y轴值。

y-axis

默认情节

Default Plot

使用实际Y轴数据绘图 Formatted Plot