Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add example with overlapping bars in a grouped bar chart #3612

Merged
merged 2 commits into from
Sep 26, 2024

Conversation

mattijn
Copy link
Contributor

@mattijn mattijn commented Sep 25, 2024

This PR adds an example that demonstrates how to create partially overlapping bars in a grouped bar chart.

The example looks as such:
image

The overlapping effect was created using the following code (method-based syntax):

import altair as alt
import pandas as pd

source = pd.DataFrame(
    {
        "category": list("AABBCC"),
        "group": list("xyxyxy"),
        "value": [0.1, 0.6, 0.7, 0.2, 0.6, 0.1],
    }
)

base = alt.Chart(source, width=alt.Step(12)).encode(
    x="category:N",
    y="value:Q",
    xOffset=alt.XOffset("group:N").scale(paddingOuter=0.5),
)

alt.layer(
    base.mark_bar(size=20, stroke="white", fillOpacity=0.9).encode(fill="group:N"),
    base.mark_text(dy=-5).encode(text="value:Q"),
)

Explanation:

  • The partial overlap is achieved by controlling the allocated space for each bar and its actual size.
  • width=alt.Step(12) in alt.Chart() defines the space allocated for each bar and thus defines the amount of overlap.
  • mark_bar(size=20) sets the actual width of the bars.
  • The paddingOuter=0.5 parameter in the xOffset scale creates spacing between the categories along the x-axis, to make sure the groups are distinct

Copy link
Member

@dangotbanned dangotbanned left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Liking this @mattijn!

I had one suggestion on the labels, but since I'm not fully convinced on my alternative I'm happy to approve as is

@mattijn
Copy link
Contributor Author

mattijn commented Sep 26, 2024

Thanks for your review, I will open a new PR with another example based on your suggestion to have text overlay on the bars instead of the text above the bars. That also will highlight an issue that I hope becomes easier to write with your work on expressions (edit: done per #3614).

@mattijn mattijn enabled auto-merge (squash) September 26, 2024 18:11
@mattijn mattijn merged commit 38ce5b1 into main Sep 26, 2024
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants