多行时间序列按属性在另一个数据帧中进行颜色编码(pandas / R上为plotly / ggplot2)

道尔顿

我有一个典型的股票价格面板数据框,其中date是索引,每列代表一只股票(因此,项(i,j)是j在日期i的股票价格)。在另一个数据框中,我还具有有关每种股票背后的公司行业的信息。我想绘制一个时间序列图(x ='Date'),每只股票有一条线。我要注意的是,我还希望使用第二个数据框按行业对行进行颜色编码。

最终目标是要有一个交互式图形,因此可以直接在python中使用plotly完成,也可以通过R进行操作,首先是ggplot2对象,然后可以使用plotly读取该对象。

对于最小的可复制示例,可以将这些.csv文件读取为python / R:

#df1
Date, StockA, StockB, StockC
2020-01-02, 1, 1, 1
2020-01-03, 2, 1, 3
2020-01-04, 4, 2, 5

#df2
, Stock, Industry
0, StockA, IndustryI
1, StockB, IndustryII
2, StockC, IndustryI

通过阅读R中的这些内容,您将获得:

> dput(df1)
structure(list(Date = c("2020-01-02", "2020-01-03", "2020-01-04"
), StockA = c(1L, 2L, 4L), StockB = c(1L, 1L, 2L), StockC = c(1L, 
3L, 5L)), class = "data.frame", row.names = c(NA, -3L))
> dput(df2)
structure(list(X = 0:2, Stock = c(" StockA", " StockB", " StockC"
), Industry = c(" IndustryI", " IndustryII", " IndustryI")), class = "data.frame", row.names = c(NA, 
-3L))
bb1

使用Python:

import pandas as pd
df1 = pd.DataFrame({'Date': ['2020-01-02', '2020-01-03', '2020-01-04'],
 'StockA': [1, 2, 4],
 'StockB': [1, 1, 2],
 'StockC': [1, 3, 5]})

df2 = pd.DataFrame({'Stock': ['StockA', 'StockB', 'StockC'],
 'Industry': ['IndustryI', 'IndustryII', 'IndustryI']})

使用长格式的库存和行业数据创建一个数据框:

df3 = pd.merge(df1.melt(id_vars="Date", var_name="Stock", value_name="Price"),
               df2,
               on="Stock",
               how="left")

这给出了:

   Date        Stock      Price    Industry
0  2020-01-02  StockA     1        IndustryI
1  2020-01-03  StockA     2        IndustryI
2  2020-01-04  StockA     4        IndustryI
3  2020-01-02  StockB     1        IndustryII
4  2020-01-03  StockB     1        IndustryII
5  2020-01-04  StockB     2        IndustryII
6  2020-01-02  StockC     1        IndustryI
7  2020-01-03  StockC     3        IndustryI
8  2020-01-04  StockC     5        IndustryI

然后使用Plotly Express创建图:

import plotly.express as px
px.line(df3, x="Date", y="Price", color="Industry", line_group="Stock")

股票价格

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章