【问题标题】:How would one mimic the geom_col() function from the R library ggplot in the Python package Altair?如何模仿 Python 包 Altair 中的 R 库 ggplot 中的 geom_col() 函数?
【发布时间】:2020-07-31 23:10:32
【问题描述】:

我正在尝试使用 Altair 绘制柱形图,但是 Altair 中没有 mark_column() 方法。如何使用 Altairs mark_bar() 方法模拟 geom_col() 的功能?

【问题讨论】:

    标签: python r ggplot2 altair


    【解决方案1】:

    来自ggplot2 docs

    有两种类型的条形图:geom_bar()geom_col()geom_bar() 使条形的高度与每组中的案例数成正比(或者如果提供了重量美学,则为重量的总和)。如果您希望条形的高度表示数据中的值,请改用geom_col()

    听起来他们之间的区别不是标记,而是标记代表什么价值。在 Altair 中,标记表示的值是通过编码定义的。

    所以 Altair 版本的 geom_bar() 可能看起来像这样:

    data = pd.DataFrame({
      'category': ['A', 'A', 'B', 'B', 'B', 'C']
    })
    
    alt.Chart(data).mark_bar().encode(
      x='category:N',
      y='count():Q'
    )
    

    或者,对于具有重量美学的geom_bar()

    data = pd.DataFrame({
      'category': ['A', 'A', 'B', 'B', 'B', 'C'],
      'weights': [1, 2, 1, 2, 3, 2]
    })
    
    alt.Chart(data).mark_bar().encode(
      x='category:N',
      y='sum(weights):Q'
    )
    

    Altair 版本的 geom_col() 可能如下所示:

    data = pd.DataFrame({
      'category': ['A', 'B', 'C'],
      'value': [4.1, 6.3, 2.2]
    })
    
    alt.Chart(data).mark_bar().encode(
      x='category:N',
      y='value:Q'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 2018-07-03
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多