Altair color encoding changes apparent bar values

Viewed 33

Here is the current code for my visualization and the chart it produces:

base = alt.Chart(cs_data).mark_bar().encode(x=alt.X("PROGRAM:N", axis=alt.Axis(title='University/Credit Level', labels=False)), 
                                     y=alt.Y('MD_EARN_WNE:Q', axis=alt.Axis(title='Median Graduate Salary')),
                                     ).properties(
    width=480,
    height=320
)
                                     
credit_labels = base.mark_text(align='left', baseline='middle', angle=270, dx=3, color='black').encode(
    text='CREDDESC:O'
)

chart = base.mark_bar().encode(
    color=alt.Color("INSTNM", title="University")
)

final = alt.layer(chart, credit_labels, data=cs_data)

final

https://i.stack.imgur.com/pvFcC.png

As you can see, the text seems to be misaligned for the two orange bars. They are actually aligned to where the bar should end, but an extra bit gets added to the bar.

If I remove the color encoding this goes away:

base = alt.Chart(cs_data).mark_bar().encode(x=alt.X("PROGRAM:N", axis=alt.Axis(title='University/Credit Level', labels=False)), 
                                     y=alt.Y('MD_EARN_WNE:Q', axis=alt.Axis(title='Median Graduate Salary')),
                                     ).properties(
    width=480,
    height=320
)
                                     
credit_labels = base.mark_text(align='left', baseline='middle', angle=270, dx=3, color='black').encode(
    text='CREDDESC:O'
)

chart = base.mark_bar().encode(
  
)

final = alt.layer(chart, credit_labels, data=cs_data)

final

https://i.stack.imgur.com/MNVBY.png

What's going on here?

1 Answers

It seems you are overplotting for these 2 bars. With the color encoding, the bars get stacked, without they are just overlayed on each other. You can also see that the text is bolder, because these are 2 labels overlapping.
A fix would be to use y=alt.Y('sum(MD_EARN_WNE):Q') to sum the overlapping bars. It would be good to look in the data and find the dataframe column which is causing this grouping, so you understand what you are exactly plotting.

Related