问题
I just installed plotly express. And I am trying to do something simple - plot each column of my data frame on the same y-axis with the index as x-axis. Here are questions/observations:
Is it necessary for the data frame to have index as a column to be used as x-axis ? Can I not directly use the index for x-axis? How can I add multiple traces as were called in plotly on y-axis for the same x-axis ?
Please note that, I am not trying to add traces using plotly, rather trying to use plotly-express.
Also, there a few similar posts online, the closest was this: https://community.plot.ly/t/multiple-traces-plotly-express/23360 However, this post shows how you can add a scatter, not a line. I want to plot a line and there is no add_line similar to add_scatter shown in the example here.
Appreciate any help in advance
Sample code:
import plotly.express as px
import pandas as pd
import numpy as np
# Get some data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
# Plot
fig = px.line(df, x='Date', y='AAPL.High')
# Only thing I figured is - I could do this
fig.add_scatter(x=df['Date'], y=df['AAPL.Low']) # Not what is desired - need a line
# Show plot
fig.show()
PLot:
回答1:
Your code works fine! But if you specifically do not want to apply the (somewhat laborious) add_trace()
function to each line, you can use px.line()
. This will require you to transform your data from a wide to long format though. But that's easy and well worth the effort. Here's how you do it using pandas and plotly:
Code:
# imports
import plotly.express as px
import pandas as pd
import numpy as np
# data
df_wide = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df_long=pd.melt(df_wide, id_vars=['Date'], value_vars=['AAPL.Open', 'AAPL.High', 'AAPL.Low', 'AAPL.Close', 'mavg'])
# plotly
fig = px.line(df_long, x='Date', y='value', color='variable')
# Show plot
fig.show()
Plot:
回答2:
Not sure what type of line your looking for, but have you tried something like below
fig.add_scatter(x=df['Date'], y=df['AAPL.Low'],mode='lines')
On a standard scatter you can set the mode to be any combination of lines, markers and text.
来源:https://stackoverflow.com/questions/58142058/how-to-plot-multiple-lines-on-the-same-y-axis-using-plotly-express-in-python