Vega lite使用一个数据字段作为轴,另一个数据字段作为标签

时间:2017-08-22 10:17:12

标签: svg charts axis-labels vega vega-lite

Vega Lite中,是否可以使用数据值的一个字段作为轴值,另一个字段作为标签?

如果这是我的vega lite规范,那么图表可以正常工作,但会在x轴上显示日期。如何在x轴上显示日期名称?

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.json",
  "description": "basic line graph",
  "data": {
    "values": [
        {"date":"2017-08-15", "dayName":"Tue","item":"foo","count":"0"},
        {"date":"2017-08-16", "dayName":"Wed","item":"foo","count":"11"},
        {"date":"2017-08-17", "dayName":"Thu","item":"foo","count":"7"},
        {"date":"2017-08-18", "dayName":"Fri","item":"foo","count":"28"},
        {"date":"2017-08-19", "dayName":"Sat","item":"foo","count":"0"},
        {"date":"2017-08-20", "dayName":"Sun","item":"foo","count":"0"},
        {"date":"2017-08-21", "dayName":"Mon","item":"foo","count":"0"}
    ]},
  "mark": {
    "type": "line",
    "interpolate": "monotone"
  },
  "encoding": {
    "x": {"field": "date", "type": "temporal"},
    "y": {"field": "count", "type": "quantitative"}
  }
}

enter image description here

它在x轴上显示日期字段August 16August 17。如何让它显示dayName字段呢?它应该显示TueWed等等。

1 个答案:

答案 0 :(得分:1)

您可以使用timeUnit

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.json",
  "description": "basic line graph",
  "data": {
    "values": [
        {"date":"2017-08-15", "dayName":"Tue","item":"foo","count":"0"},
        {"date":"2017-08-16", "dayName":"Wed","item":"foo","count":"11"},
        {"date":"2017-08-17", "dayName":"Thu","item":"foo","count":"7"},
        {"date":"2017-08-18", "dayName":"Fri","item":"foo","count":"28"},
        {"date":"2017-08-19", "dayName":"Sat","item":"foo","count":"0"},
        {"date":"2017-08-20", "dayName":"Sun","item":"foo","count":"0"},
        {"date":"2017-08-21", "dayName":"Mon","item":"foo","count":"0"}
    ]},
  "mark": {
    "type": "line",
    "interpolate": "monotone"
  },
  "encoding": {
    "x": {
      "timeUnit": "day",
      "field": "date", 
      "type": "temporal"
    },
    "y": {"field": "count", "type": "quantitative"}
  }
}

如果您想自定义标签格式,您还可以添加axis format