2

I have the following dataframe with date stamps and 2 columns:

              Gold  Oil
2000-03-31  276.75  29.89
2000-06-30  288.15  31.83

I am trying to build the plotly chart where i should put the "date" as an "x" but the output gives me an error of "date" ----> not a column of dataframe as expected [Gold, Oil].

below is the graph i am trying to build:

import plotly.express as px
import pandas as pd
df = gold_data
fig = px.line(df,x='Date', y='Gold', title='GOLD Time Series with Rangeslider')
fig.update_xaxes(rangeslider_visible=True)
fig.show()

How do i add the Dates as a column to pandas dataframe so i can call it in the graph? I believe its something to do with index bit not 100% sure. Thanks for your help!

vestland
  • 55,229
  • 37
  • 187
  • 305
  • 1
    Your dates are in the index, and the index doesn't have a name. You can reset the index (i.e., have an index that doesn't depend on the dates you have) using the Pandas function `reset_index`. You'll have to name the dates column too. –  Nov 10 '20 at 02:32
  • 1
    This will help you. https://stackoverflow.com/questions/57178206/use-pandas-index-in-plotly-express – Canasta Nov 10 '20 at 02:33
  • new_df=gold_data.copy() new_df1=new_df.reset_index() new_df1.columns=["Date","Gold",......]''' – user14496743 Nov 10 '20 at 02:51

1 Answers1

1

You can name your index using df.index.name = 'Date', and then change your call to px like this:

df.index.name = 'Date'
fig = px.line(df,x=df.index, y='Gold', title='GOLD Time Series with Rangeslider')

Even though you can't directly use x='Date' above, plotly will know what's up and include the index name in the plot:

Plot

enter image description here

Complete code:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'Gold': {'2000-03-31': 276.75, '2000-06-30': 288.15},
                   'Oil': {'2000-03-31': 29.89, '2000-06-30': 31.83}})

df.index.name = 'Date'

fig = px.line(df,x=df.index, y='Gold', title='GOLD Time Series with Rangeslider')
fig.update_xaxes(rangeslider_visible=True)
fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305