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!

3
  • 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. Commented Nov 10, 2020 at 2:32
  • 1
    This will help you. stackoverflow.com/questions/57178206/… Commented Nov 10, 2020 at 2:33
  • new_df=gold_data.copy() new_df1=new_df.reset_index() new_df1.columns=["Date","Gold",......]''' Commented Nov 10, 2020 at 2:51

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.