Reputation: 47
I'm trying to recreate this chart in Altair but can't figure out how to make a few minor edits: https://datawrapper.dwcdn.net/E0jaK/1/
Here's my current progress: https://i.sstatic.net/NMkmO.jpg
The three edits I'm trying to figure out are:
How to left-align y-axis labels
How to add spacing between the labels and the y-axis
How to move bar number labels to the base of the bars instead of the ends
Any insight on how to implement these edits would be great.
Here's the raw data:
Crime,Count
Larceny/Theft,739
Assault,177
Burglary/Breaking & Entering,133
Destruction of Property/Vandalism,128
Drugs,107
Motor Vehicle Theft,95
Fraud,71
Sex Offenses,57
Suspicious Activity,45
Trespassing,23
Family Offenses,22
Weapons Violations,21
This is the theme I used:
def chart_theme():
font = "Calibri"
return {
"width": 700,
"height": 300,
"background": "white",
"config": {
"title": {
"fontSize": 20,
"anchor": "start"
},
"axisY": {
"labelFont": font,
"labelFontSize": 13,
"labelLimit":200,
"ticks": False,
"titleFont": font,
"titleFontSize": 12,
"titleAlign":"right",
"titleAngle": 0,
"titleY": -10,
"titleX": 25,
},
"view":{"stroke": "transparent",
},
}
}
And here's the chart code:
base = alt.Chart(df, title='San Francisco Crime (11/05 - 11/11)').encode(
x=alt.X('Count', axis=None),
y=alt.Y('Crime', title='Crimes reported to SFPD, by top complaint',
sort=list(df.Crime.values)))
bars = base.mark_bar(size=22).encode(color=alt.condition(
alt.datum.Count > 700,
alt.value('#e17700'),
alt.value('#00648e')))
text = base.mark_text(
color='white',
align='right',
size=12,
dx=-3
).encode(
text='Count')
chart = bars + text
chart
Any guidance/suggestions would be greatly appreciated.
Upvotes: 0
Views: 4230
Reputation: 1354
How about something like this
import pandas as pd
import altair as alt
data = {'Larceny/Theft':739,
'Assault':177,
'Burglary/Breaking & Entering':133,
'Destruction of Property/Vandalism':128,
'Drugs':107,
'Motor Vehicle Theft':95,
'Fraud':71,
'Sex Offenses':57,
'Suspicious Activity':45,
'Trespassing':23,
'Family Offenses':22,
'Weapons Violations':21}
df = pd.DataFrame(list(data.items()), columns=['Crime', 'Count'])
base = alt.Chart(df, title='San Francisco Crime (11/05 - 11/11)').encode(
x=alt.X('Count', axis=None),
y=alt.Y('Crime', title='Crimes reported to SFPD, by top complaint',
sort=list(df.Crime.values)))
bars = base.mark_bar(size=22).encode(color=alt.condition(
alt.datum.Count > 700,
alt.value('#e17700'),
alt.value('#00648e')))
text = alt.Chart(df).mark_text(
color='white',
align='left',
x=3
).encode(alt.Text('Count:N'), alt.Y('Crime', sort=list(df.Crime.values)))
chart = bars + text
chart.properties(width=700).configure_axisY(
titleAngle=0,
titleY=-10,
titleX=-60,
labelPadding=160,
labelAlign='left'
)
Upvotes: 7