生生不息

生生不息

AI用Ploty绘制交互式图像

2025-06-22
AI用Ploty绘制交互式图像

提示词

现在有一个DataFrame,包含收盘价和简单收益,请用Ploty绘制子图来展示这两列。

答案

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np

# 生成模拟数据(替换为您的DataFrame)
dates = pd.date_range('2024-01-01', periods=100)
df = pd.DataFrame({
    'close': 100 + np.cumsum(np.random.normal(0, 2, 100)),  # 收盘价
    'return': np.random.normal(0.01, 0.03, 100)  # 简单收益(正负波动)
}, index=dates)

# 创建2行1列的子图布局(共享x轴)
fig = make_subplots(
    rows=2,
    cols=1,
    shared_xaxes=True,  # 关键:共享x轴实现联动[4,7](@ref)
    vertical_spacing=0.1,  # 子图间距优化[7](@ref)
    subplot_titles=('收盘价走势', '简单收益波动')  # 子图标题[6](@ref)
)

# 添加收盘价折线图(上子图)
fig.add_trace(
    go.Scatter(
        x=df.index,
        y=df['close'],
        mode='lines',
        name='收盘价',
        line=dict(color='#1f77b4', width=2),
        hovertemplate='日期:%{x}<br>收盘价:%{y:.2f}<extra></extra>'  # 悬停格式
    ),
    row=1, col=1
)

# 添加收益柱状图(下子图)
fig.add_trace(
    go.Bar(
        x=df.index,
        y=df['return'],
        name='收益',
        marker=dict(
            color=np.where(df['return'] > 0, '#2ca02c', '#d62727'),  # 红跌绿涨
            line=dict(width=0)  # 无边框
        ),
        hovertemplate='日期:%{x}<br>收益:%{y:.4f}<extra></extra>'
    ),
    row=2, col=1
)

# 统一布局设置
fig.update_layout(
    height=600,
    title_text='股票价格与收益分析',
    hovermode='x unified',  # 鼠标悬停时双图数据联动[10](@ref)
    legend=dict(orientation='h', yanchor='bottom', y=1.02)  # 水平图例[7](@ref)
)

# 坐标轴标签设置
fig.update_yaxes(title_text="价格", row=1, col=1)
fig.update_yaxes(title_text="收益率", row=2, col=1)
fig.update_xaxes(title_text="日期", row=2, col=1)  # 仅底部子图显示x轴标题

# 显示图表
fig.show()

图像: