Home > Blockchain >  How to plot a variable dataframe
How to plot a variable dataframe

Time:02-03

I have a dataframe with a variable number of stock prices. In other words, I have to be able to plot the entire Dataframe, because I may encounter 1 to 10 stocks prices. The x axis are dates, the Y axis are Stock prices. Here is a sample of my Df:

 df = pd.DataFrame(all_Assets)
 df2 = df.transpose()
 print(df2)
                                Close       Close       Close
Date                                                         
2018-12-12 00:00:00-05:00   40.802803   24.440001  104.500526
2018-12-13 00:00:00-05:00   41.249191   25.119333  104.854965
2018-12-14 00:00:00-05:00   39.929325   24.380667  101.578560
2018-12-17 00:00:00-05:00   39.557732   23.228001   98.570381
2018-12-18 00:00:00-05:00   40.071678   22.468666   99.605057

This is not working

fig = go.Figure(data=go.Scatter(df2, mode='lines'),)

I need to plot this entire dataframe on a single chart, with 3 different lines. But the code has to adapt automatically if there is a fourth stock, fifth stock e.g. By the way , I want it to be a Logarithmic plot.

CodePudding user response:

There is a sample in the enter image description here

  • express long format
df_long = df.melt(id_vars='date', value_vars=df.columns[1:],var_name='ticker')
px.line(df_long, x='date', y='value', color='ticker')
  • graph_objects wide format
import plotly.graph_objects as go

fig = go.Figure()

for ticker in df.columns[1:]:
    fig.add_trace(go.Scatter(x=df['date'], y=df[ticker], name=ticker))

fig.show()
  • graph_objects long format
fig = go.Figure()

for ticker in df_long.ticker.unique():
    dff = df_long.query('ticker == @ticker')
    fig.add_trace(go.Scatter(x=dff['date'], y=dff['value'], name=ticker))

fig.show()

CodePudding user response:

I recommend you to use pandas.DataFrame.plot. A minimal working example for your case should be just

df2.plot()

. Then just play around with the plot() method and your df2 dataframe to get exactly the output you need.

  • Related