【发布时间】:2021-06-23 21:32:57
【问题描述】:
我非常喜欢 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)
四个问题:
- 如何用纯色##D9E9F0 填充背景?
如何使第一行弹出(通过在粗体标签上添加框 “杰里米·科尔宾”)?
我可以在左下角添加浅灰色的版权声明吗 版本 3 中新的 Altair 文本层可能性的角落? 如果是这样,该怎么做?
- 如何将 xticks 放在图表顶部?
感谢您的帮助!
更新来自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')
【问题讨论】:
标签: python data-visualization altair