Is there a way to transform a nominal DataFrame into a Bubble Plot in Altair?

Viewed 46

I have the following code:

test_dict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f'], 'C': ['g', 'h', 'i'],
            'D': ['j', 'k', 'l'], 'E': ['m', 'n', 'o'], 'F': ['p', 'q', 'r'],
            'G': ['s', 't', 'u'], 'H': ['v', 'w', 'x']}

test_df = pd.DataFrame(test_dict)

which produces the following DataFrame:

dataframe

Is there a way to transform this into a BubblePlot in Altair? I want the columns (A - H) to make up the y-axis, and I want there to be a bubble for each entry in the column (so in this case, three entries per column). Can this be done?

1 Answers

You have wide-form data that you need to transform to long-form data (See See Wide-form vs. Long-form data in Altair's docs). You can generally address this with the Fold Transform:

import pandas as pd
import altair as alt

test_dict = {'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f'], 'C': ['g', 'h', 'i'],
             'D': ['j', 'k', 'l'], 'E': ['m', 'n', 'o'], 'F': ['p', 'q', 'r'],
             'G': ['s', 't', 'u'], 'H': ['v', 'w', 'x']}

test_df = pd.DataFrame(test_dict)

alt.Chart(test_df).transform_fold(
    list(test_df.columns), as_=['key', 'value']
).mark_point().encode(
    x='value:N',
    y='key:N',
)

enter image description here

Related