我非常喜欢Altair用Python制作图形。作为致敬,我想重新生成"Mistakes, we’ve drawn a few"中的“经济学家”图:
这是第一枪的代码:
import numpy as np
import pandas as pd
import altair as alt
df = pd.read_csv('http://infographics.economist.com/databank/Economist_corbyn.csv').dropna()
bars = alt.Chart(df, title="Average number of likes per Facebook post").mark_bar().
encode(
y=alt.Y('Page:O', axis=alt.Axis(title=''),
sort=alt.EncodingSortField(
field="Average number of likes per Facebook post 2016:Q", # The field to use for the sort
op="sum", # The operation to run on the field prior to sorting
order="ascending" # The order to sort in
)),
color=alt.value("#116EA1"),
x=alt.X("Average number of likes per Facebook post 2016:Q",
axis=alt.Axis(title='Average number of likes per Facebook post')),
)
text = bars.mark_text(
align='left',
baseline='middle',
dx=3, # Nudges text to right so it doesn't appear on top of the bar,
).encode(
text='Average number of likes per Facebook post 2016:Q'
)
(bars+text).configure_title(fontSize=14)
四个问题:
如何弹出第一行(通过在粗体标签上添加框 'Jeremy Corbyn')吗?
我可以在左下方添加浅灰色的版权声明吗? 在第3版中使用新的Altair文字图层的可能性如何? 如果是这样,该怎么做?
感谢帮助!
使用jakevdp和aberna中的(1)和(4)答案进行更新:
df['x'] = df['Average number of likes per Facebook post 2016']/1000.0
bars = alt.Chart(
df, title="Average number of likes per Facebook post ('000)"
).mark_bar().encode(
y=alt.Y('Page:O', axis=alt.Axis(title=''),
sort=alt.EncodingSortField(
field="Average number of likes per Facebook post 2016:Q", # The field to use for the sort
op="sum", # The operation to run on the field prior to sorting
order="ascending" # The order to sort in
)),
color=alt.value("#116EA1"),
x=alt.X("x:Q",
axis=alt.Axis(title='', orient="top"),
scale=alt.Scale(round=True, domain=[0,5])),
)
bars.configure_title(fontSize=14).configure(background='#D9E9F0')
答案 0 :(得分:2)
回答您的一个问题:您可以使用configure(background="colorname")
添加背景。例如:
(bars+text).configure_title(fontSize=14).configure(background='#DDEEFF')
答案 1 :(得分:1)
回答第4个问题,您需要在alt.Axis中使用orient="top"
参数。
axis=alt.Axis(title='Average number of likes per Facebook post',orient="top"))
答案 2 :(得分:1)