微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vega Lite:标准化堆积条形图 + 以文本形式叠加百分比

如何解决Vega Lite:标准化堆积条形图 + 以文本形式叠加百分比

我有一个类似于这样的堆叠标准化条形图: https://vega.github.io/editor/#/examples/vega-lite/stacked_bar_normalize 我正在尝试将相关百分比(每个条形段)显示为类似于以下内容的条形文本:https://gist.github.com/pratapvardhan/00800a4981d43a84efdba0c4cf8ee2e1

我尝试添加一个转换字段来计算百分比,但经过数小时的尝试仍然无法使其正常工作。 我失去了帮助? 我最好的尝试:

{
  "description":
    "A bar chart showing the US population distribution of age groups and gender in 2000.","data": {
    "url": "data/population.json"
  },"transform": [
    {"filter": "datum.year == 2000"},{"calculate": "datum.sex == 2 ? 'Female' : 'Male'","as": "gender"},{
      "stack": "people","offset": "normalize","as": ["v1","v2"],"groupby": ["age"],"sort": [{"field": "gender","order": "descending"}]
    }
  ],"encoding": {
    "y": {
      "field": "v1","type": "quantitative","title": "population"
    },"y2": {"field": "v2"},"x": {
      "field": "age","type": "ordinal"
    },"color": {
      "field": "gender","type": "nominal","scale": {
        "range": ["#675193","#ca8861"]
      }
    }
  },"layer":[
{ "mark": "bar"},{"mark": {"type": "text","dx": 0,"dy": 0},"encoding": {
        "color":{"value":"black"},"text": { "field": "v1","format": ".1f"}}
    }

  ]
}

解决方法

您可以使用 joinaggregate transform 对每个组进行标准化,然后使用 "format": ".1%" 将分数显示为百分比。使用它,无需手动计算堆栈变换;通过编码指定堆栈更简单,如您链接的示例所示。

这是结果 (open in editor):

{
  "description": "A bar chart showing the US population distribution of age groups and gender in 2000.","data": {"url": "data/population.json"},"transform": [
    {"filter": "datum.year == 2000"},{"calculate": "datum.sex == 2 ? 'Female' : 'Male'","as": "gender"},{
      "joinaggregate": [{"op": "sum","field": "people","as": "total"}],"groupby": ["age"]
    },{"calculate": "datum.people / datum.total","as": "fraction"}
  ],"encoding": {
    "y": {
      "aggregate": "sum","title": "population","stack": "normalize"
    },"order": {"field": "gender","sort": "descending"},"x": {"field": "age","type": "ordinal"},"color": {
      "field": "gender","type": "nominal","scale": {"range": ["#675193","#ca8861"]}
    }
  },"layer": [
    {"mark": "bar"},{
      "mark": {"type": "text","dx": 20,"dy": 0,"angle": 90},"encoding": {
        "color": {"value": "white"},"text": {"field": "fraction","type": "quantitative","format": ".1%"}
      }
    }
  ]
}

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?