如何在Altair中创建分组条形图? [英] How to create a grouped bar chart in Altair?

查看:78
本文介绍了如何在Altair中创建分组条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Altair中创建分组条形图?我正在尝试以下操作,但它只是并排生成两个图形。

How does one create a grouped bar chart in Altair? I'm trying the following but it is just producing two graphs side by side.

Chart(data).mark_bar().encode(
   column='Gender',
   x='Genre',
   y='Rating',
   color='Gender'
)

推荐答案

组条形图示例

我显示了分组条形图。您还可以在此处中查看完整文档。

I show a simplified example of Grouped Bar Chart from Altair's documentation. You can also see the full documentation here.

基本上,您必须将x轴性别(每个子图中的F或M)指定为y轴,并将其指定为 Rating 类型作为

Basically, you have to specify x-axis Gender (F or M in each subplot), y-axis as Rating and Genre as Column.

from altair import *
import pandas as pd

# create dataframe
df = pd.DataFrame([['Action', 5, 'F'], 
                   ['Crime', 10, 'F'], 
                   ['Action', 3, 'M'], 
                   ['Crime', 9, 'M']], 
                  columns=['Genre', 'Rating', 'Gender'])

chart = Chart(df).mark_bar().encode(
   column=Column('Genre'),
   x=X('Gender'),
   y=Y('Rating'),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display() # will show the plot

条形图看起来像l追随者

The bar chart will look like following

添加Axis参数

您只需要遵循 Axis 文档中的参数以使绘图看起来更漂亮:

You only have to follow Axis parameters in documentation to make the plot looks prettier:

chart = Chart(df).mark_bar().encode(
   column=Column('Genre', 
                 axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),
                 scale=Scale(padding=4.0)),
   x=X('Gender', axis=False),
   y=Y('Rating', axis=Axis(grid=False)),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display()

这篇关于如何在Altair中创建分组条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆