问题
Apologies if this has been asked before, but I'm looking for a way to create bar-charts that are "dodged" (language from ggplot2
) using the Altair library in python.
I know Altair has this example:
import altair as alt
from vega_datasets import data
source = data.barley()
alt.Chart(source).mark_bar().encode(
x='year:O',
y='sum(yield):Q',
color='year:N',
column='site:N'
)
That produces this plot:
However, this has a lot of redundant labels and information. Ideally I want a plot where the paired bars encode the year in colour (blue is 1931 and orange is 1932) and then the cities running along the x-axis (ordinal variable).
Hard to explain, but here's an example of how to get a plot like this from seaborn (using different data; source isthis SO question):
回答1:
Yes, you've found the recommended way to create grouped bar charts in Altair. If you want to adjust the final look of the chart, you can do things like removing & rearranging labels and titles; here's how you might modify your example to make it closer to the seaborn chart:
import altair as alt
from vega_datasets import data
source = data.barley()
alt.Chart(source).mark_bar().encode(
x=alt.X('year:O', axis=alt.Axis(title=None, labels=False, ticks=False)),
y=alt.Y('sum(yield):Q', axis=alt.Axis(grid=False)),
color='year:N',
column=alt.Column('site:N', header=alt.Header(title=None, labelOrient='bottom'))
).configure_view(
stroke='transparent'
)
回答2:
In case anyone ends up here through google etc, here's the code to bring the bars closer together:
import altair as alt
from vega_datasets import data
source = data.barley()
alt.Chart(source).mark_bar().encode(
alt.X('year:O', axis=None),#axis=alt.Axis(title=None, labels=False, ticks=False)),
alt.Y('sum(yield):Q', axis=alt.Axis(grid=True)),
alt.Facet('site:N',title="Facet title Here",),
color='year:N',
).properties(height=150, width=80).configure_view(
stroke='transparent'
).configure_scale(bandPaddingInner=0,
bandPaddingOuter=0.1,
).configure_header(labelOrient='bottom',
labelPadding = 3).configure_facet(spacing=5
)
Result:
Thanks to Jake for pointing me in the right direction with his answer!
来源:https://stackoverflow.com/questions/58618197/produce-dodged-or-side-by-side-bar-column-charts-in-altair