Search code examples
pythonplotlyinteractiveplotly-python

matplotlib to plotly plot conversion


I wanted to create an interactive plot with matplotlib in google colab. It seems like a complex task so I want a little help to convert this piece of code which is in matplotlib to Plotly.

close = df['A']
fig = plt.figure(figsize = (15,5))
plt.plot(close, color='r', lw=2.)
plt.plot(close, '^', markersize=10, color='m', label = 'signal X', markevery = df_x)
plt.plot(close, 'v', markersize=10, color='k', label = 'signal Y', markevery = df_y)
plt.title('Turtle Agent: total gains %f, total investment %f%%'%(df_A, df_B))
plt.legend()
plt.show()

enter image description here


Solution

    • using sample data from plotly OHLC examples https://plotly.com/python/ohlc-charts/
      1. create a line trace
      2. add scatter traces based on filters of data frame with required formatting. This is done as a list comprehension, could be done as inline code
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    df = pd.read_csv(
        "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv"
    )
    df["Date"] = pd.to_datetime(df["Date"])
    # make data set more useful for demonstrating this plot
    df.loc[df.sample((len(df)//8)*7).index, "direction"] = np.nan
    
    px.line(df, x="Date", y="AAPL.Close").update_traces(line_color="red").add_traces(
        [
            px.scatter(
                df.loc[df["direction"].eq(filter)], x="Date", y="AAPL.Close"
            )
            .update_traces(marker=fmt)
            .data[0]
            for filter, fmt in zip(
                ["Increasing", "Decreasing"],
                [
                    {"color": "black", "symbol": "triangle-up", "size": 10},
                    {"color": "blue", "symbol": "triangle-down", "size": 10},
                ],
            )
        ]
    )
    

    enter image description here