I'm stumped on how to display ticks for all x-axis values but only labels for some. The x-axis values in my chart are 0.0 - 3.0 in tenths, whereas I only want to display labels for the whole numbers (0, 1, 2, 3).
Here's the data I'm working with:
bin count
0.0 0
0.1 0
0.2 0
0.3 0
0.4 0
0.5 0
0.6 0
0.7 0
0.8 0
0.9 0
1.0 0
1.1 1
1.2 3
1.3 7
1.4 14
1.5 13
1.6 29
1.7 47
1.8 59
1.9 59
2.0 75
2.1 72
2.2 103
2.3 96
2.4 119
2.5 76
2.6 93
2.7 68
2.8 70
2.9 44
3.0 49
The only progress I could manage was setting the data type to Ordinal and increasing the label font size:
alt.Chart(df).mark_bar().encode(x=alt.X('bin:O', axis=alt.Axis(labelFontSize=18,
values=[round(i,1) for i in np.arange(0,3.1,.1)])),
y=alt.Y('count:Q'))
This is what the chart looks like: altair bar chart
Any suggestions?
You can use the tickCount
axis property to specify how many ticks you would like, and the labels are automatically chosen so that they will not overlap:
import altair as alt
import pandas as pd
df = pd.DataFrame({
'bin': [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5,
1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0],
'count': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 7, 14, 13, 29, 47,
59, 59, 75, 72, 103, 96, 119, 76, 93, 68, 70, 44, 49]
})
alt.Chart(df).mark_bar().encode(
x=alt.X('bin:Q', axis=alt.Axis(tickCount=df.shape[0], grid=False)),
y=alt.Y('count:Q')
)
If you want to further customize the label locations and text, you can use a labelExpr. For example:
alt.Chart(df).mark_bar().encode(
x=alt.X('bin:Q', axis=alt.Axis(
tickCount=df.shape[0],
grid=False,
labelExpr="datum.value % 1 ? null : datum.label"
)),
y=alt.Y('count:Q')
)