如何将第二个 y 轴添加到条形图?牵牛星

时间:2021-02-25 17:10:14

标签: python python-3.x altair

我有一个数据框:

  EMOJI   PERCENT_TEXT    PERCENT     combined
0  ?         23.1%        23.1       ? 23.1%
1  ?         5.7%          5.7       ? 5.7% 
2  ?         3.5%          3.5       ? 3.5%
3  ?         3.0%          3.0       ? 3.0%
4  ?         2.5%          2.5       ? 2.5%
5  ??          2.4%          2.4        ??  2.4%

我的代码如下:

bars = alt.Chart(percentages_df).mark_bar(color='orange').encode(
    alt.X('PERCENT:Q',axis=None),
    alt.Y('combined:N', sort='-x', title=None)
).configure_view(strokeOpacity=0).configure_axis(
    # remove axis line
    grid=False, domain=False,ticks=False
)

enter image description here

但是我创建的图表并不是我所期望的。

我想用 Altair 创建一个带有两个 y 轴标签的条形图,如下所示: enter image description here

我应该使用图层来生成这个图表吗?如果是这样,如何生成两个 y 轴标签的图层?如果没有,我应该用什么来生成它? 谢谢!

2 个答案:

答案 0 :(得分:2)

我不知道有什么简单的方法可以创建两组不同的轴标签,但是您可以通过调整轴标签属性来大致完成您想要的对齐。

我还更改了图表以使用转换创建组合标签:

import pandas as pd
import altair as alt

percentages_df = pd.DataFrame({
  'EMOJI': ['?', '?', '?', '?', '?', '??'],
  'PERCENT': [23.1, 5.7, 3.5, 3.0, 2.5, 2.4]
})

alt.Chart(percentages_df).transform_calculate(
    combined = alt.datum.EMOJI + '    ' + alt.datum.PERCENT + '%'
).mark_bar(color='orange').encode(
    alt.X('PERCENT:Q',axis=None),
    alt.Y('combined:N', sort='-x', title=None,
          axis=alt.Axis(labelAlign='left', labelPadding=6))
).configure_view(strokeOpacity=0).configure_axis(
    # remove axis line
    grid=False, domain=False,ticks=False
)

chart

另一种选择是连接两个图表,其中一个没有 x 编码:

import pandas as pd
import altair as alt

percentages_df = pd.DataFrame({
  'EMOJI': ['?', '?', '?', '?', '?', '??'],
  'PERCENT': [23.1, 5.7, 3.5, 3.0, 2.5, 2.4]
})

chart = alt.Chart(percentages_df).mark_bar(color='orange').encode(
    alt.X('PERCENT:Q',axis=None),
    alt.Y('PERCENT:N', sort='-x', title=None)
)

left = alt.Chart(percentages_df).mark_text().encode(
    alt.Y('EMOJI:N', sort=alt.EncodingSortField('PERCENT', order="descending"), title=None)
)

alt.hconcat(
    left, right
).configure_view(strokeOpacity=0).configure_axis(
    # remove axis line
    grid=False, domain=False,ticks=False
)

chart 2

答案 1 :(得分:0)

您也可以尝试通过 rjust 用空格填充用于标记的字符串。为此,您必须使用等宽字体,以便所有字符都等于:

# With your df above
df['LABEL'] = df['EMOJI'] + df['PERCENT_TEXT'].str.rjust(8)

alt.Chart(df).mark_bar(color='orange').encode(
    alt.X('PERCENT:Q',axis=None),
    alt.Y('LABEL:N', sort='-x', title=None, axis=alt.Axis(labelFont='Droid Sans Mono'))
).configure_view(strokeOpacity=0).configure_axis(
    grid=False, domain=False,ticks=False
)

enter image description here