You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用Plotly绘制单X轴双折线图?DataFrame绘图遇NameError错误

Fixing NameError and Plotting Dual Line Charts with Plotly for Your DataFrame

First, let's break down the NameError you're hitting:

NameError: name 'Amount' is not defined

This error pops up because you're referencing Amount directly, but it’s a column in your result DataFrame—you need to prefix it with result. to access it properly.

Beyond fixing that, Plotly works best with structured DataFrames, so let’s adjust your code to replicate the Matplotlib behavior correctly. Here are two reliable approaches:

Approach 1: Using Plotly Express with a Combined Long-Format DataFrame

This method fits Plotly Express’s design by restructuring your data into a long format, making it easy to add color coding for the two periods:

import pandas as pd
import plotly.express as px

# Split data into two periods and add a label column
first_period = result.iloc[:362][["Date", "Amount"]].assign(Period="First 362 Days")
remaining_period = result.iloc[362:][["Date", "Amount"]].assign(Period="Remaining Days")

# Combine into a single DataFrame
combined_data = pd.concat([first_period, remaining_period])

# Create the line chart
fig = px.line(
    combined_data,
    x="Date",
    y="Amount",
    color="Period",
    template="plotly_dark",
    title="Credit Amount by Date",
    labels={"Amount": "Credit Amount", "Date": "Date"}
)
fig.show()

Approach 2: Using Plotly Graph Objects (Similar to Matplotlib's Step-by-Step Workflow)

If you prefer a workflow that mirrors your Matplotlib code, use plotly.graph_objects to add each line as a separate trace:

import plotly.graph_objects as go

# Initialize an empty figure
fig = go.Figure()

# Add first line trace
fig.add_trace(go.Scatter(
    x=result.Date[:362],
    y=result.Amount[:362],
    mode="lines",
    name="First 362 Days"
))

# Add second line trace
fig.add_trace(go.Scatter(
    x=result.Date[362:],
    y=result.Amount[362:],
    mode="lines",
    name="Remaining Days"
))

# Update layout to match your preferences
fig.update_layout(
    template="plotly_dark",
    title="Credit Amount by Date",
    xaxis_title="Date",
    yaxis_title="Credit Amount",
    font=dict(size=14)
)
fig.show()

Why Your Original Code Failed

Your original line y=[Amount[:362], Amount[362:]] had two key issues:

  1. Amount wasn’t prefixed with result., so Python couldn’t locate the variable.
  2. Even if you fixed that to y=[result.Amount[:362], result.Amount[362:]], Plotly Express expects y to be either a single column name or list of column names (not raw Series slices). The approaches above avoid this by structuring the data correctly.

内容的提问来源于stack exchange,提问作者Nithin Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:52:49