RobinHood
RobinHood

Reputation: 407

Plotly lines using start and end dates

I have a DataFrame with the columns: start date, end date, and value. How can I plot one line for each start-end date in Plotly?

Example:

import pandas as pd
import plotly.express as px
df = pd.DataFrame({"start date": [1,2,3,4], "end date":[8,7,4,9], "value":[11,3,11,4]})
fig = px.line(df, x=["start date","end date"], y="value")
fig.show()

In this case, there are only two lines for the columns start date and end date. However, what I'm looking for is 1 line for each start-end date. I tried with the parameter color="value" but, in value 11 it only plots 1 line. I could print it with simple plot of plt as:

import matplotlib.pyplot as plt
x = [df["start date"], df["end date"]]
y = [df["value"], df["value"]]
plt.plot(x, y)
plt.show()

Upvotes: 1

Views: 3636

Answers (2)

Roy2012
Roy2012

Reputation: 12493

To create multiple 'indepent' lines, you'll have to create several traces, like in the example below:

import pandas as pd
import plotly.graph_objs as go

df = pd.DataFrame({"start date": [1,2,3,4], "end date":[8,7,4,9], "value":[11,3,11,4]})

fig = go.Figure()
for (start, end, value) in zip(df["start date"], df["end date"], df["value"]):
    name = f"{start} to {end}"
    fig.add_trace(go.Scatter(x=[start, end], y=[value, value],
                    mode='lines', name = name))    


fig.show()

The result is:

enter image description here

Upvotes: 2

ilja
ilja

Reputation: 2682

Actually your plot contains both lines at y=11, but they are blue & green and so hard to distinguish. But you can use custom colors, e.g.:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

colors = ['blue', 'red', 'yellow', 'green']
for x1, x2, y, c in zip(df["start date"], df["end date"], df["value"], colors):
    plt.plot([x1, x2], [y, y], color=c)

enter image description here

Upvotes: 0

Related Questions