简体   繁体   中英

Altair scatter plot to bar chart single select row of data frame

A newbie question for Altair visualization lib in Python. I have a pandas dataframe, all columns are numeric but one column is a string label (see below). I am trying to build interactive chart, binding scatter plot single selection to bar chart. The bar chart will show rest of the numeric values, X axis will be column name, Y axis will be numeric values. All examples are related to aggregation. How can visualize it in Altair? See representative data below. The label value will be used to select the row.

Label Score 1 Score 2 Score 3
red 0.22 0.55. 0.44
blue 0.45 0.66. 0.33
green 0.45 0.66. 0.33
black 0.45 0.66. 0.33

What I try to do similar to following but no aggregation: https://altair-viz.github.io/gallery/scatter_with_layered_histogram.html

It's not clear what you want shown in the interactive scatter plot mentioned in the description, but I can answer your question about the bar chart.

If you want column names on the x-axis of a chart, the way to do this is to use a Fold Transform , which folds together several columns into a column of keys and a column of values.

For your data, it might look like this (using color scale=None so that the actual colors in the data are used):

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'Label': ['red', 'blue', 'green', 'black'],
    'Score 1': [0.22, 0.45, 0.45, 0.45],
    'Score 2': [0.55, 0.66, 0.66, 0.66],
    'Score 3': [0.44, 0.33, 0.33, 0.33],
})

alt.Chart(df).transform_fold(
    ['Score 1', 'Score 2', 'Score 3'], as_=['column', 'value']
).mark_bar().encode(
    x='column:N',
    y='value:Q',
    color=alt.Color('Label:N', scale=None)
)

在此处输入图像描述

(Side note: in the future, consider presenting your representative data in the form of executable code like the pandas DataFrame I used above, rather than in the form of a formatted table).

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