求助:如何用Plotly绘制单X轴双折线图?DataFrame绘图遇NameError错误
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:
Amountwasn’t prefixed withresult., so Python couldn’t locate the variable.- Even if you fixed that to
y=[result.Amount[:362], result.Amount[362:]], Plotly Express expectsyto 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

