python - 调整 Altair 分组条形图的标签

标签 python plot bar-chart axis-labels altair

我有一个名为table的数据框:

TERM                        Bitcoin       S&P500    Real Estate Gold
0   High-Inflation/ Short term  3097.94       -3700.78  761.23      6512.71
1   High-Inflation/ Mid term    —             -3080.01  -8434.66    3242.40
2   High-Inflation/ Long term   —             -2089.25  -9117.96    8174.43
3   Low-Inflation/ Short term   780200.00     -273.71   1824.72     2214.51
4   Low-Inflation/ Mid term     21013600.00   5331.40   35810.58    -2879.37
5   Low-Inflation/ Long term    978017143.00. 15045.41  35895.81    861.90

并使用以下代码生成了一个图表:

from itertools import product
alt.Chart(table).transform_fold(
    ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
).mark_bar().encode(
    x="key:N",
    y=alt.Y("value:Q", scale=alt.Scale(type='symlog'),
           axis=alt.Axis(values=[0] + [10**x * y for (x, y) in product(range(1, 10, 1), (1, -0.01))])),
    color="key:N",
    column="TERM",
)

但是,正如您所看到的,顶部的标签被挤在一起了。我不知道如何使这些更具视觉吸引力,以及如何删除每个图表的 x 轴上的 key 标签:

chart

最佳答案

您可以通过在 x 编码中设置 title=None 来删除 x 标题。您可以通过用行列表替换有问题的字符串来添加换行符。例如:

table['TERM'] = table['TERM'].str.split(' ', 1)
alt.Chart(table).transform_fold(
    ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
).mark_bar().encode(
    x=alt.X("key:N", title=None),
    y=alt.Y("value:Q", scale=alt.Scale(type='symlog'),
           axis=alt.Axis(values=[0] + [10**x * y for (x, y) in product(range(1, 10, 1), (1, -0.01))])),
    color="key:N",
    column="TERM"
)

enter image description here

关于python - 调整 Altair 分组条形图的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70841887/

相关文章:

svg - 如何在 SVG 中创建这个形状?

r - 带有数据点的 barplot() - base R

python - 有没有办法在 Python 的 re.sub() 中的替换字符串中使用正则表达式?

python - 识别列表中接近 Python 给定数字的非零元素

python - 如何使用 boto3 将 S3 中的单个 Parquet 文件读入 Pandas 数据帧?

r - 使用 ggplot2 生成 "fuzzy"RD 图

python - 删除 pandas plot.area 的抗锯齿

python - (Python) 如何向 Pandas 绘图添加工具提示?

python - Python 查找两个元组中的对应项

python - 带有 matplotlib 的长垂直条形图