2

I try to use plotly in python to plot several lines having their own X-values on the same graph for example.

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)

x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

I want to plot this on the one x-axis from 1 to 10.
All answers on StackOverFlow (like this) describe the solution with a pandas dataframe where all lines (y1 and y2) have the same array of x-values corresponding to each line. However, in my case y1 and y2 have different (though in the same units) corresponding x-values.

What can I do to make such a plot in plotly?

2 Answers2

5

When you don't have a dataframe, I argue that the easiest way is to use plotly.graph_objects.

import plotly.graph_objects as go

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)
x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

f1 = go.Figure(
    data = [
        go.Scatter(x=x1, y=y1, name="first"),
        go.Scatter(x=x2, y=y2, name="second"),
    ],
    layout = {"xaxis": {"title": "x axis"}, "yaxis": {"title": "y axis"}, "title": "My title"}
)
f1

enter image description here

You can also use the plotly.express module, however it requires a bit more code to set the names on the legends.

Learn more at this documentation page.

Davide_sd
  • 10,578
  • 3
  • 18
  • 30
3

With just a little bit of data wrangling on your example data, you can just use this single line:

fig = px.line(df, x = 'x', y = 'y', color = 'name', markers = True)

And get this:

enter image description here

The wrangling is just building two dataframes out of your categegories and stacking them into a so-called long form which plotly express handles beautifully. Contrary to so-called wide form data, it won't matter if the different categories have a different number of observations.

Complete code:

import plotly.express as px
import pandas as pd
import numpy as np

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)

x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

df1 = pd.DataFrame({'name': ['1']*len(x1),
                    'x': x1,
                    'y': y1})

df2 = pd.DataFrame({'name': ['2']*len(x2),
                    'x': x2,
                    'y': y2})

df = pd.concat([df1, df2])

fig = px.line(df, x = 'x', y = 'y', color = 'name', markers = True)
fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305