Python3 MatPlotLib:我如何获得多线图

时间:2015-08-02 21:58:12

标签: python pandas matplotlib graph plot

我有一个像这样的元组列表:

list_months = [ ('A', 'January'),
                ('A', 'January'),
                ('A', 'January'),  # Total 10 instances of ('A', 'January')
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'February'),
                ('A', 'February'),
                .............
                ('B', 'January'),
                ('B', 'January'),  # Total 15 instances of ('B', 'January')
                ('B', 'July'),
                ('B', 'July'),
                ............. ]

这是通过Pandas数据帧使用:

获得的
for index, val in b['Incident Reported Date Time'].iteritems():
    list_months.append((index, str(val)))

我希望能够生成MatPlotLib图,以便:
X轴 - >月
Y轴 - >体积
多个彩色线 - >每个代表A' B' B' C'等等。


enter image description here

例如,在此图片中,红线代表A'和蓝线' B' 由于有10个(' A',' 1月和#39;)它在1月的Y轴上显示10的红线,并且有15个(' ; B',1月')所以它在1月的Y轴显示15的蓝线。

如何在matplotlib中为Python3动态生成此图例和图例?
图表应该是示例图像中的折线图。

1 个答案:

答案 0 :(得分:3)

如果将数据保留在DataFrame中,将更容易绘制。我使用您帖子中的示例数据制作了一个示例DataFrame:

list_months = [ ('A', 'January'),
                ('A', 'January'),
                ('A', 'January'),  # Total 10 instances of ('A', 'January')
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'February'),
                ('A', 'February'),
                ('B', 'January'),
                ('B', 'January'),  # Total 15 instances of ('B', 'January')
                ('B', 'July'),
                ('B', 'July')
            ]
d = pandas.DataFrame(list_months, columns=["Item", "Month"]).fillna(0)

>>> d
   Item     Month
0     A   January
1     A   January
2     A   January
3     A     March
4     A     March
5     A     March
6     A  February
7     A  February
8     B   January
9     B   January
10    B      July
11    B      July

然后你可以轻松搞定你的情节:

>>> d.groupby(['Month', 'Item']).size().unstack().loc[['January', 'February', 'March', 'July']].fillna(0).plot(kind='line')

enter image description here

.loc['January', 'February', ...]位只需要按时间顺序而不是字母顺序获取月份。从长远来看,您最好通过日期时间对象或代表月份的数字存储此信息。)