向 Altair 图形添加背景实心填充

cas*_*t42 2 python data-visualization altair

我非常喜欢 Altair 用 Python 制作图表。作为致敬,我想重新生成“错误,我们画了一些”中的经济学人图: 在此处输入图片说明 这是第一次拍摄的代码:

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

四个问题:

  1. 如何用纯色 ##D9E9F0 填充背景?
  2. 如何使第一行弹出(通过在粗体标签“Jeremy Corbyn”上添加框)?

  3. 我可以在版本 3 中使用新的 Altair 文本层可能性在左下角添加浅灰色版权声明吗?如果是这样,该怎么做?

  4. 我怎样才能把 xticks 放在图表的顶部?

感谢帮助 !

更新来自jakevdpaberna 的(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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

jak*_*vdp 5

回答您的一个问题:您可以使用configure(background="colorname"). 例如:

(bars+text).configure_title(fontSize=14).configure(background='#DDEEFF')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明