hathawayj
hathawayj

Reputation: 240

Altair conditional coloring of points

Problem

I am trying to simply color by two numerical conditions. I can get the chart to work with one condition. However, my inexperience with conditioning in Python and JavaScript leaves me wondering what I am doing wrong when I add two conditions.

Import packages and load data

import pandas as pd
import altair as alt
mpg = pd.read_csv("https://github.com/byuidatascience/data4python4ds/raw/master/data-raw/mpg/mpg.csv")

I want this subset of data to be colored red

mpg[mpg.displ.gt(5) & mpg.hwy.gt(20)]

First color one condition chart that works

(base.
  encode(x = 'displ',
         y = 'hwy',
         color = alt.condition((datum.displ > 5), 
                                alt.ColorValue('red'), 
                                alt.ColorValue('black'))).
  mark_point()
)

Second plot with two conditions doesn't color according to the condition

(base.
  encode(x = 'displ',
         y = 'hwy',
         color = alt.condition((datum.displ > 5) & (datum.mpg > 20), 
                                alt.ColorValue('red'), 
                                alt.ColorValue('black'))).
  mark_point()
)

Upvotes: 1

Views: 1972

Answers (1)

hathawayj
hathawayj

Reputation: 240

Well...

there is not an mpg variable in my data frame. Mapping to the correct column fixes my issue. I wish an error reported.


(base.
  encode(x = 'displ',
         y = 'hwy',
         color = alt.condition((datum.displ > 5) & (datum.hwy > 20), 
                                alt.ColorValue('red'), 
                                alt.ColorValue('black'))).
  mark_point()
)

Upvotes: 1

Related Questions