0

我正在使用字典用 python 和 matplotlib 绘制线条我无法弄清楚为什么我的线条的颜色没有改变

from datetime import datetime
import matplotlib.pyplot as plt


dico =  {'A01': [(u'11/10/12-08:00:01', 2.0), (u'11/10/12-08:10:00', 10.0), \
                 (u'11/10/12-08:20:01', 5.0), (u'11/10/12-08:30:01', 15.0), \
                 (u'11/10/12-08:40:00', 7.0), (u'11/10/12-08:50:01', 45.0)],
         'A02': [(u'11/10/12-08:00:01', 10.0), (u'11/10/12-08:10:00', 12.0), \
                 (u'11/10/12-08:20:01', 15.0), (u'11/10/12-08:30:01', 10.0), \
                 (u'11/10/12-08:40:00', 17.0), (u'11/10/12-08:50:01', 14.0)]}

x = []
y = []
lstPlot = []
plt.gca().set_color_cycle(["b", "g", "r", "c", "m", "y", "k"])
for key, values in dico.iteritems():
    for i in  sorted(values):
        # date sting to date obj
        dateObj = datetime.strptime(i[0], "%d/%m/%y-%H:%M:%S")
        line = dateObj, i[1]
        lstPlot.append(line)
    for i in sorted(lstPlot):
        x.append(i[0])
        y.append(i[1])
    plt.plot(x, y, label=key)



# plotting

plt.legend(loc='upper right')
plt.xlabel('Dates')
plt.ylabel("titre")
plt.title("Modbus")
plt.show()

请注意,我在图例中有不同的颜色,但在情节中没有。

4

2 回答 2

3

它们正在发生变化,但您正在将一个与另一个重叠。这些线

x = []
y = []
lstPlot = []

需要循环内。否则lstPlot只会增长。例如,print lstPlot在循环内添加会给出:

[(datetime.datetime(2012, 10, 11, 8, 0, 1), 10.0), (datetime.datetime(2012, 10, 11, 8, 10), 12.0), (datetime.datetime(2012, 10, 11, 8, 20, 1), 15.0), (datetime.datetime(2012, 10, 11, 8, 30, 1), 10.0), (datetime.datetime(2012, 10, 11, 8, 40), 17.0), (datetime.datetime(2012, 10, 11, 8, 50, 1), 14.0)]
[(datetime.datetime(2012, 10, 11, 8, 0, 1), 10.0), (datetime.datetime(2012, 10, 11, 8, 10), 12.0), (datetime.datetime(2012, 10, 11, 8, 20, 1), 15.0), (datetime.datetime(2012, 10, 11, 8, 30, 1), 10.0), (datetime.datetime(2012, 10, 11, 8, 40), 17.0), (datetime.datetime(2012, 10, 11, 8, 50, 1), 14.0), (datetime.datetime(2012, 10, 11, 8, 0, 1), 2.0), (datetime.datetime(2012, 10, 11, 8, 10), 10.0), (datetime.datetime(2012, 10, 11, 8, 20, 1), 5.0), (datetime.datetime(2012, 10, 11, 8, 30, 1), 15.0), (datetime.datetime(2012, 10, 11, 8, 40), 7.0), (datetime.datetime(2012, 10, 11, 8, 50, 1), 45.0)]

(您可能需要滚动查看第二个列表比第一个列表长很多,但您应该注意到第一个值在两者中是相同的。)

所以你可以清除里面的列表,或者你可以稍微简化一下:

for key, values in dico.iteritems():
    points = [(datetime.strptime(i[0], "%d/%m/%y-%H:%M:%S"), i[1]) for i in values]
    points.sort()
    x, y = zip(*points)
    plt.plot(x, y, label=key)

该代码,加上@bmu 的建议

plt.gcf().autofmt_xdate()

自动使 x 轴看起来不错,产生

固定图像

[或者,您可能希望使用get_xticklabels()和 等方法set_rotation进行更精细的控制。]

于 2012-10-15T16:15:37.417 回答
1

尝试 :

colors = ["b", "g", "r", "c", "m", "y", "k"]
for (key, values), c in zip(dico.iteritems(), colors):
    ...
    plt.plot(x, y, c, label=key)
于 2012-10-15T16:16:12.497 回答