Altair distinct and count not plotting expected value

Viewed 372

I am trying to plot the number of unique values in a column containing strings on the y axis as follows:

alt.Chart(as_df).mark_bar(color='firebrick').encode(
    alt.X('TimeUTC:T', title='Day',axis=alt.AxisConfig(labelAngle=45)), 
    alt.Y('distinct(FlightID)', type='nominal', title='Number of flights')
)

My data is of the form:

TimeUTC FlightID Latitude Longitude
2021-01-01 06:05:00.079745+00:00 2021-01-01 06:05:00+00:00 a706014b-02d0-424a-a346-2bd25ffa8e08 42.3323
2021-01-01 06:05:00.291337+00:00 2021-01-01 06:05:00+00:00 d2e2bd67-c95a-426d-9357-a717d6c9124d 42.3434
2021-01-01 06:06:00.131817+00:00 2021-01-01 06:06:00+00:00 a706014b-02d0-424a-a346-2bd25ffa8e08 42.3323
2021-01-01 06:06:00.219178+00:00 2021-01-01 06:06:00+00:00 d2e2bd67-c95a-426d-9357-a717d6c9124d 42.3434

The result is this chart:

enter image description here

If I count the number of unique FlightIDs on Feb 9th, I get:

foo = as_df['20210209':'20210209']
foo.FlightID.nunique()
58

Why is the chart showing a maximum number of unique FlightIDs as 12 when there is at least one day with 58?

python: 3.9.7 altair: 4.1.0

1 Answers

In the chart, you are grouping the x axis by timestamp, whereas in the pandas aggregation, you are grouping the data by date (i.e. stripping the hours and minutes).

If you would like to group the x axis by date in the chart, you can do something like this:

alt.Chart(as_df).mark_bar(color='firebrick').encode(
    alt.X('yearmonthdate(TimeUTC):T', title='Day',axis=alt.AxisConfig(labelAngle=45)), 
    alt.Y('distinct(FlightID)', type='nominal', title='Number of flights')
)
Related