简体   繁体   中英

How to plot multiple lines in one plotly chart from same column from the same pandas dataframe?

I have the following df as pandas:

Name        X           Y              Location number

Ford        651536.216  4767758.137    250
Ford        651485.4353 4767685.615    161.4
Chevrolet   651536.791  4767758.958    251
Chevrolet   651542.525  4767767.147    261
Golf        651579.0758 4767819.347    324.7
Golf        651543.8153 4767768.99     263.2
Toyota      651579.0758 4767819.347    324.7
Toyota      651590.676  4767835.914    344.9
Renault     651513.011  4767674.872    26.97
Renault     651511.373  4767676.018    24.5
...

I have over hundred manufacturers name in a name column. I want to plot all the manufacturers in one plot using line chart.

df_1 = df[df['Name'] == 'Ford']

df_2 = df[df['Name'] == 'Chevrolet']

df_3 = df[df['Name'] == 'Golf']

df_4 = df[df['Name'] == 'Toyota']

df_5 = df[df['Name'] == 'Renault']

I was able to achieve what I wanted by individually pointing manufacturers name from df and saving it to new df.

df_sorted1 = df_1.sort_values('Location number')
.
.
df_sorted6 = df_5.sort_values('Location number')

fig.add_trace(go.Scatter(x=df_1 ['x'], y=df_1 ['y'], mode='lines'))
fig.add_trace(go.Scatter(x=df_2 ['x'], y=df_2 ['y'], mode='lines'))
fig.add_trace(go.Scatter(x=df_3 ['x'], y=df_3 ['y'], mode='lines'))
fig.add_trace(go.Scatter(x=df_4 ['x'], y=df_4 ['y'], mode='lines'))
fig.add_trace(go.Scatter(x=df_5 ['x'], y=df_5 ['y'], mode='lines'))

What I want is to plot every manufacturers from one column. X, Y is coordinates and location number is sorted because I want to start plotting from first location to latest

Try this code

df = df.sort_values(['Name', 'Location number'])

import plotly_express as px

px.line(df, x='X', y='Y', color='Name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM