将自定义图例(标记颜色)添加到绘图python

时间:2019-02-15 08:31:35

标签: python plotly legend

我试图用可视化的方式可视化交易算法。我有两个数据框:一个是采用我的算法执行的收盘价,另一个是进行交易的框。绿点代表买入,红色代表卖出。我还想要一个菜单​​,以便能够选择要分析的库存。目前,一切都通过在收盘价之上采取行动来起作用。

问题是:如何在特定位置添加有关点颜色的图例(绿色表示购买,红色表示出售)?

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import pandas as pd
init_notebook_mode(connected=True)

feed = pd.DataFrame({'AAPL': [100, 120, 130, 120, 150],
                     'MSFT': [80, 70, 90, 100, 99]}, index = pd.date_range('2018-01-01', '2018-01-05'))

trans = pd.DataFrame({'Symbol': ['AAPL', 'AAPL', 'MSFT', 'MSFT'],
                        'Amount': [2, 1, 3, 1],
                        'Action': ['buy', 'sell', 'buy', 'sell'],
                        'Price': [120, 150, 70, 100],
                        'Date': [pd.to_datetime(i) for i in ['2018-01-02', '2018-01-05', '2018-01-02', '2018-01-04']]
                       })

data = []
all_but = dict(label = 'All',
               method = 'update',
                  args = [{'visible': [True] * len(feed.columns.tolist())},
                          {'title': 'all'}
                           ])
buttonlist = [all_but]
for col in feed.columns.tolist():
    stock = go.Scatter(x=feed.index,
                       y=feed.loc[:, col],
                       name=col
                      )
    #actions
    success = trans.loc[trans.Symbol == col]
    actions = go.Scatter(x=success.Date,
                         y=success.Price,
                         name='',
                         mode = 'markers',
                         text = ['Amount ' + str(amount) for amount in success.Amount],
                         hoverinfo = 'text',
                         showlegend=False,
                         marker = dict(
                             size=10,
                             color = ['green' if i == 'buy' else 'red' for i in success.Action]

                         )
                        )
    data.append(stock)
    data.append(actions)
    button = dict(label = col,
                  method = 'update',
                  args = [{'visible': [col == i for i in feed.columns.tolist() for _ in range(2)]},
                          {'title': 'title' + col}
                           ])
    buttonlist.append(button)

updatemenus = list([
    dict(active=-1,
         buttons=buttonlist,
    )
])
layout = dict(title='Feed', showlegend=True,
              updatemenus=updatemenus)

fig = dict(data=data, layout=layout)
iplot(fig)

enter image description here

P.S .:我将很高兴提出关于更简单的方法的建议,就像我是新手一样。

1 个答案:

答案 0 :(得分:2)