matplotlib 到 plotly plot 转换

matplotlib to plotly plot conversion

我想在 google colab 中使用 matplotlib 创建交互式绘图。这似乎是一项复杂的任务,所以我需要一些帮助来将 matplotlib 中的这段代码转换为 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()

  • 使用来自 plotly OHLC 示例 https://plotly.com/python/ohlc-charts/ 的示例数据
    1. 创建线条跟踪
    2. 根据具有所需格式的数据框过滤器添加散点图。这是作为 list 理解完成的,可以作为内联代码
    3. 完成
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},
            ],
        )
    ]
)