首页 > 解决方案 > matplotlib:使用 matplotlib 或 seaborn 显示每个日期的所有产品价格的折线图

问题描述

如何使用折线图在一张图表中显示每个日期的所有产品价格?

数据框有三列,就像:

+---------+-------+----------+
| product | price |   date   |
+---------+-------+----------+
| pen     |     1 | 20190101 |
| apple   |     2 | 20190101 |
| book    |     3 | 20190101 |
| cup     |     4 | 20190101 |
| pen     |   0.8 | 20190102 |
| apple   |   2.2 | 20190102 |
| book    |   3.1 | 20190102 |
| cup     |   3.5 | 20190102 |
| pen     |   0.6 | 20190103 |
| apple   |   2.6 | 20190103 |
| book    |   2.1 | 20190103 |
| cup     |   4.3 | 20190103 |
+---------+-------+----------+

在此处输入图像描述

标签: pythonpython-3.xpandasmatplotlibseaborn

解决方案


假设您的数据框:

import pandas as pd

df = pd.DataFrame({'product':['pen','apple','book','cup','pen','apple','book','cup','pen','apple','book','cup',],
                   'price':[1,2,3,4,0.8,2.2,3.1,3.5,.6,2.6,2.1,4.3],
                   'date':['20190101','20190101','20190101','20190101','20190102','20190102','20190102','20190102','20190103','20190103','20190103','20190103']})

您可以使用pandas.DataFrame.groupby对产品进行分组并matplotlib绘制每种产品的价格:

import matplotlib.pyplot as plt

for i in df.groupby('product'):
    plt.plot(i[1].date,i[1].price,'-o',label=i[0])

plt.legend(loc='upper center',
           bbox_to_anchor=(0.5, -0.2),
           fancybox=True,
           shadow=True,
           ncol=4)
plt.xlabel('date')
plt.ylabel('price')
plt.show()

在此处输入图像描述


推荐阅读