如何模拟Python包Altair中的R库ggplot中的geom_col()函数?

2024-10-02 10:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法功能绘制barcolumncolmarkgeom
1条回答
网友
1楼 · 发布于 2024-10-02 10:30:20

ggplot2 docs开始:

There are two types of bar charts: geom_bar() and geom_col(). geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.

听起来它们之间的区别不在于标记,而在于标记所代表的价值。在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'
)

牵牛星版本的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'
)

相关问题 更多 >

    热门问题