【问题标题】:Increasing bar width in bar chart using Altair使用 Altair 增加条形图中的条形宽度
【发布时间】:2018-02-10 20:08:14
【问题描述】:

我有以下数据框,并想在 Python 中使用 altair 库来绘制我的条形图。但是,我不知道如何扩展每个条的宽度(与matplotlib 中的width=0.5 参数相同)。

import pandas as pd 
from altair import * 

ls = [[   1,  734], [   2, 1705], [   3, 2309],
      [   4, 2404], [   5, 2022], [   6, 1538],
      [   7, 1095], [   8,  770], [   9,  485],
      [  10,  312], [  11,  237], [  12,  153],
      [  13,  103], [  14,   69], [  15,   47],
      [  16,   39], [  17,   43], [  18,   28],
      [  19,   18]]
df = pd.DataFrame(ls, columns=['n_authors', 'n_posters'])

这里是使用altair的绘图函数

bar_chart = Chart(df).mark_bar().encode(
    x=X('n_authors', title='Number of Authors in a Poster'), 
    y=Y('n_posters', title='Number of Posters'),
).configure_facet_cell(
    strokeWidth=1.0,
    height=200,
    width=300
 )
bar_chart.display()

脚本中的情节如下所示:

【问题讨论】:

    标签: python altair


    【解决方案1】:

    您需要使用barSize 参数。在此处查看更多Mark Configuration

    解决方案

    bar_chart = Chart(df).mark_bar(barSize=20).encode(
        x=X('n_authors', title='Number of Authors in a Poster'), 
        y=Y('n_posters', title='Number of Posters'),
    ).configure_facet_cell(
        strokeWidth=1.0,
        height=200,
        width=300
     )
    bar_chart.display()
    

    输出

    【讨论】:

    • 谢谢@Nipun!我看了一会儿configure_facet_cell。我不知道你可以在mark_bar马上配置。
    • 乐于助人! :)
    • 仅供参考,barSize 属性不再有效。应该改用size
    【解决方案2】:

    @Nipun 的答案不再有效。经过一些实验,我可以使用size 而不是barSize 获得所需的结果。 (我只在 Jupyter Lab 中测试过。)

    from pandas import *
    from altair import *
    
    ls = [[   1,  734], [   2, 1705], [   3, 2309],
          [   4, 2404], [   5, 2022], [   6, 1538],
          [   7, 1095], [   8,  770], [   9,  485],]
    df = DataFrame(ls, columns=['X', 'Y'])
    
    Chart(df).mark_bar(size=20).encode(x='X', y='Y')
    

    【讨论】:

    • 您是否也找到了增加间距的方法?当尺寸像这样增加时,它开始与相邻的酒吧重叠。
    • @Tarantula 你应该只增加情节的宽度;例如Chart(df).mark_bar(size=20).encode(x='X', y='Y').properties(width=800)
    • 有没有办法在使用交互式时通过缩放来缩放?