1

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()
2
  • To make sure I got it right: for each line, you’d like x1 and x2 to be the start and end date, respectively, and y1 and y2 to be the values? Commented May 29, 2020 at 16:19
  • Yes, but in this case, y1 == y2, which means it is a horizontal line. Commented May 29, 2020 at 16:22

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

So it seems that there is no way to do it with px.line, right? Anyway, your solution is what I am looking for. Thank you. Do you know how to add the information panel in all the line not only in the start-end points?
Yes, having the hover text in all the line not only in the points.
0

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

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.