vega-lite - Vega-lite 以 SI 单位显示文本值
问题描述
我的示例源代码如下
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"a": "A", "b": 28000}, {"a": "B", "b": 55000},
{"a": "C", "b": 43000}, {"a": "D", "b": 91000},
{"a": "E", "b": 81000}, {"a": "F", "b": 53000},
{"a": "G", "b": 19000}, {"a": "H", "b": 87000},
{"a": "I", "b": 52000}
]
},
"encoding": {
"x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
"y": {"field": "b", "type": "quantitative"}
},
"layer": [{
"mark": "bar"
},
{
"mark":{
"type":"text",
"align":"center",
"baseline":"middle",
"dx":0,
"dy":-5
} ,
"encoding":{
"text":{"field":"b","type":"quantitative"}
}
}
]
}
我希望文本标记以 SI 单位动态显示。所以在我的例子中,28k
, 55k
,43k
等等。
我怎样才能在 Vega-lite 中做到这一点?
解决方案
在您的文本中添加格式化程序,如下所示或在编辑器中:
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"a": "A", "b": 28000},
{"a": "B", "b": 55000},
{"a": "C", "b": 43000},
{"a": "D", "b": 91000},
{"a": "E", "b": 81000},
{"a": "F", "b": 53000},
{"a": "G", "b": 19000},
{"a": "H", "b": 87000}
]
},
"encoding": {
"x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
"y": {"field": "b", "type": "quantitative"}
},
"layer": [
{"mark": "bar"},
{
"mark": {
"type": "text",
"align": "center",
"baseline": "middle",
"dx": 0,
"dy": -5
},
"encoding": {
"text": {"field": "b", "type": "quantitative", "format": ".2s"}
}
}
]
}
编辑
要在不同的值范围上提供不同的格式,您可以简单地执行calculate
转换并根据条件创建格式化的值。然后,只需使用 value 字段,text
如下所示或参考editor。
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"a": "A", "b": 28000},
{"a": "B", "b": 55000},
{"a": "C", "b": 43000},
{"a": "D", "b": 91000},
{"a": "E", "b": 81000},
{"a": "F", "b": 53000},
{"a": "G", "b": 19000},
{"a": "H", "b": 87000},
{"a": "I", "b": 523399}
]
},
"transform": [
{
"calculate": "datum.b > 99999 ? format(datum.b,'.3s') : format(datum.b,'.2s')",
"as": "textValue"
}
],
"encoding": {
"x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
"y": {"field": "b", "type": "quantitative"}
},
"layer": [
{"mark": "bar"},
{
"mark": {
"type": "text",
"align": "center",
"baseline": "middle",
"dx": 0,
"dy": -5
},
"encoding": {"text": {"field": "textValue"}}
}
]
}
推荐阅读
- python - 使用 Python 将嵌套的 JSON 数据发送到 Postgres - 找不到使用 psycopg2 在表上插入空值的方法
- android - 将项目数据传递给活动
- scala - 为什么在我向类型引入参数后它会停止工作?(斯卡拉)
- laravel - 是否可以将多个值传递给 Laravel 控制器
- c# - 为什么带有返回左外连接结果的存储过程的 EF Core FromSql 重复数据记录
- android - 我什么时候应该使用对象类型与直接 Kotlin 文件
- java - 无法获取 Java 代码以将用户输入的数据分配给 Joptionpane 中的对象字段
- c++ - C++ 中的类型双关语问题
- pyspark - 从 pyspark 中的所有列名中删除空格
- java - Java 11:导入 javax.xml.ws.WebFault:“无法解析符号 ws”