Plot one series for one column with Polars dataframe and Plotly

Plot one series for one column with Polars dataframe and Plotly

Contents

Problem Description:

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.

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

Solution – 1

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

You can also use this way:

``````fig = px.line(x=df['time'], y=[df["A"],df["B"]])
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.