3

I am trying to change color of my line chart based on 'date column'. But I am getting an error

I have tried the code:

fig = px.line(df_1, x='Time_ist', y='AccelerationG', color = 'Date')
# # fig.update_layout(title_text='Acceleration on ' + str(i))
fig.show()

The error i am getting is:

KeyError: (Timestamp('2019-09-26 00:00:00'), '', '', '', '', '')
SoKu
  • 117
  • 7

1 Answers1

2

color in px.line does not not take a Timestamp as an argument. If it somehow did, I'm not sure what to expect the result to be. Perhaps a color that indicates the passage of time? I'm not sure, really. But what I'm guessing your're looking for here, is to discern the data points by either month or day of the year and illustrate it like a factor or category. I'll show how you can do the latter using an example from plotly and a suggestion from the SO post Generating random dates within a given range in pandas.

Plot:

enter image description here

The below snippet generates a bunch of random dates, extracts the month number as an integer, adds that to the iris dataset, and lets px.Scatter() use it as input for coloring.

Code:

# Load example from https://plot.ly/python/creating-and-updating-figures/
import plotly.express as px
import pandas as pd
import numpy as np

iris = px.data.iris()

# Add random dates using a suggestion from https://stackoverflow.com/questions/50559078/generating-random-dates-within-a-given-range-in-pandas
def random_dates(start, end, n, seed=1, replace=True):
    dates = pd.date_range(start, end).to_series()
    return dates.sample(n, replace=replace, random_state=seed)

dates=random_dates("20190101","20191212", len(iris), seed=1)
months=[m.month for m in dates]
iris['month']=months

fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="month")
fig.show()

If you would like to use the day of month, just change months=[m.month for m in dates] to days=[m.day for d in dates],and adjust the reference in px.Scatter from color="month" to color="days".

please let me know how this works out for you.

vestland
  • 55,229
  • 37
  • 187
  • 305