将背景实心填充添加到Altair图

时间:2019-03-28 15:43:12

标签: python data-visualization altair

我非常喜欢Altair用Python制作图形。作为致敬,我想重新生成"Mistakes, we’ve drawn a few"中的“经济学家”图: enter image description here 这是第一枪的代码:

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)

enter image description here

四个问题:

  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')

enter image description here

3 个答案:

答案 0 :(得分:2)

回答您的一个问题:您可以使用configure(background="colorname")添加背景。例如:

(bars+text).configure_title(fontSize=14).configure(background='#DDEEFF')

enter image description here

答案 1 :(得分:1)

回答第4个问题,您需要在alt.Axis中使用orient="top"参数。

axis=alt.Axis(title='Average number of likes per Facebook post',orient="top"))

enter image description here

答案 2 :(得分:1)

回答问题 2 的类型。不是突出显示栏,而是通过条件字体样式突出显示标签。

label_style = {
    "condition": [{"test" : "datum.value == 'Jeremy Corbyn'", "value": "bold"}],
    "value": "italic"
}

...

y=alt.Y("Page:N", axis=alt.Axis(title="", labelFontStyle=label_style))

Bar chart showing average number of likes per Facebook post with one bold label highlighting Jeremy Corbyn