H.Alzy
H.Alzy

Reputation: 359

plotly parallel coordinates and categories

In a dataframe, columns A and B are categorical data, while columns X and Y is numerical and continuous. How can I use plotly to draw a parallel coordinates+categories plot such that the first two y-axis corresponding to A and B are categorical, and the latter two corresponding to X and Y are numerical?

For example, consider the following data:

df = pd.DataFrame({'A':['a','a','b','b'], 
                    'B':['1','2','1','2'], 
                    'X':[5.3,6.7,3.1,0.8],
                    'Y':[0.4,0.6,3.6,4.8]})

I tried plotly.express.parallel_categories. But this treats all numerical values as categories. On the other hand, plotly.express.parallel_coordinates omits categorical columns.

Upvotes: 1

Views: 325

Answers (1)

J W
J W

Reputation: 914

You can first convert categorical data to numerical data and then use the plotly.express.parallel_coordinates function to plot the graph.

Because plotly.express.parallel_coordinates is mainly used to process numerical data, while plotly.express.parallel_categories is used to process categorical data.

Example:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'A': ['a', 'a', 'b', 'b'],
                    'B': ['1', '2', '1', '2'],
                    'X': [5.3, 6.7, 3.1, 0.8],
                    'Y': [0.4, 0.6, 3.6, 4.8]})

#Convert categorical data to numerical data
df['A_cat'] = df['A'].astype('category').cat.codes
df['B_cat'] = df['B'].astype('category').cat.codes

# Draw parallel coordinate plot
fig = px.parallel_coordinates(df,
                               dimensions=['A_cat', 'B_cat', 'X', 'Y'],
                               labels={'A_cat': 'A', 'B_cat': 'B', 'X': 'X', 'Y': 'Y'},
                               color="X",
                               color_continuous_scale=px.colors.diverging.Tealrose,
                               color_continuous_midpoint=2)

# Update the chart layout to show the original category labels
fig.update_layout(
     xaxis=dict(
         tickvals=[0, 1, 2, 3],
         ticktext=['A', 'B', 'X', 'Y']
     )
)

fig.show()

Upvotes: 1

Related Questions