Reputation: 53
When two bar charts (one horizontal, one vertical) are shown side-by-side using alt.hconcat
, the titles are misaligned even though the heights of the charts are equal. Is there a way to align the titles?
# Makes test dataframe
test = pd.DataFrame({"group":["a","b","c"],"value1":[4,5,6], "value2":[10,12,14]}).reset_index()
# Sets up vertical bar chart
chart1 = alt.Chart(test).mark_bar().encode(
x = alt.X('group:N'),
y = alt.Y('value1:Q')
).properties(height = 300, width = 300, title = "Testing Title 1")
# Sets up horizontal bar chart
chart2 = alt.Chart(test).mark_bar().encode(
x = alt.X('value2:Q'),
y = alt.Y('group:N')
).properties(height = 300, width = 300, title = "Testing Title 2")
# Shows bar charts side by side
alt.hconcat(chart1, chart2)
The chart titles are misaligned. (can't post the image since I apparently need 10 reputation points to do so)
Upvotes: 5
Views: 1791
Reputation: 48934
It appears that this behavior is due to automatic dodging of the top tick and its label "6" from the y-axis in the leftmost chart. Altair/Vega lite probably autoadjusts the title offset to the highest element in the chart, and since the tick and its label are above the axis line, the title will be vertically offset compared to the rightmost axis where the topmost tick and its label "a" are well below the end of the axis line.
You can see that this is indeed the issue by hiding the tick label.
Current appearance from your question (red line added for comparison):
Not quite aligned, hiding the tick as well aligns them perfectly.
After removing tick and its label:
To work around this you can manually set the offset of the two titles to be the same. Unfortunately, using .configure_title(offset=0)
on the layout to set both titles at the same time does not work since it adds an offset to the values already used to for the automatic dodging.
Instead, I believe you have to set the offset with alt.TitleParams(offset=0)
for the leftmost plot or a value in the rightmost plot that brings it up to the same height as the leftmost plot. In this case, "9" seems to be the magical number
With title = alt.TitleParams("Testing Title 2", offset=9)
for the rightmost plot:
This is probably an issue/feature of Vegalite rather than Altair, so digging around on the issue tracker or posting a new issue asking them to be aligned by default might be helpful.
Upvotes: 4