1

I can't find how to plot these two series A and B with time on X.

from numpy import linspace
import polars as pl
import plotly.express as px

import plotly.io as pio
pio.renderers.default = 'browser'

times = linspace(1, 6, 10)
df = pl.DataFrame({
    'time': times,
    'A': times**2,
    'B': times**3,
})

fig = px.line(df)
fig.show()

Data keep showing as 10 series with 3 points, instead of 2 series with 10 points and the first column as X values.

enter image description here


Edit:

This line:

fig = px.line(df, x='time', y=['A', 'B'])

produces this error:

ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but received: time

Using polars 0.15.0 and plotly 5.11.0

1 Answer 1

2

You use Polars Dataframe instead of Pandas dataframe and indexing is a little different here and what is why you have this error. In order to plot it, one way to do it is to convert the dataframe from Polars to Pandas on the fly by using to_pandas():

fig = px.line(df.to_pandas(),x='time', y=['A', 'B'])

Output

enter image description here

You can also use this way:

fig = px.line(x=df['time'], y=[df["A"],df["B"]])
Sign up to request clarification or add additional context in comments.

5 Comments

Plotly is not compatible with Polars?
@mins no, Plotly is compatible with Polars, but you should select the columns correctly. Also, as you see in the second method, we do not need to convert our dataframe to Pandas dataframe.
Ah, my mistake, I didn't see the second option. That's perfect. With the second option, my legend has names like 'wide_variable_0' instead of 'A', do you know why?
@mins It is recommended by the author of Plotly is to convert it to Pandas dataframe, please read this github.com/plotly/plotly.py/issues/3637#issuecomment-1245495678
@mins , the reason of why these names in the legend are because you pass a list to y parameter and Plotly cannot infer the labels of lines from the list. Thus, Plotly label each line by default names. (wide_variable_)

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.