简体   繁体   中英

Vega-lite: How do you customize legend labels?

I have this bar chart that's made with Vega-lite (code and pic below).

But I want to customize the legend labels so that instead of videoGame it's Video Game and instead of tv its TV . Is there anyway to do this?

在此处输入图像描述

lineChart = vegalite ({
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
   "width": 560,
   "height": 200,
   "data": {"values": chartData},
   "mark": {"type": "bar"},
   "encoding": {
     "x": {"field": "year_reference", "type": "temporal", "axis": {"title": "Year", "grid": true}},
     "y": {"field": "reference_count_total", "type": "quantitative", "axis": {"title": "References", "grid": true}},
   "color": {
     "field": "title_type", 
     "scale": {
       "domain": [
         "tv",
         "movie",
         "video",
         "videoGame"
       ],
       "range": [
         "#9e9ac8",
         "#74c476",
         "#a6761d",
         "#6baed6"
       ]
     },
     "legend": true,
     "title": "Reference Type"
    },
 }

})

Just provide labelExpr in legend, where you can conditionally give the labels depending on your fields data. Refer the below code or the chart in editor

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 560,
  "height": 200,
  "data": {
    "values": [
      {
        "title_type": "tv",
        "year_reference": "10-12-2012",
        "reference_count_total": 10
      },
      {
        "title_type": "movie",
        "year_reference": "10-12-2012",
        "reference_count_total": 10
      },
      {
        "title_type": "video",
        "year_reference": "10-12-2012",
        "reference_count_total": 10
      },
      {
        "title_type": "videoGame",
        "year_reference": "10-12-2012",
        "reference_count_total": 10
      }
    ]
  },
  "mark": {"type": "bar"},
  "encoding": {
    "x": {
      "field": "year_reference",
      "type": "temporal",
      "axis": {"title": "Year", "grid": true}
    },
    "y": {
      "field": "reference_count_total",
      "type": "quantitative",
      "axis": {"title": "References", "grid": true}
    },
    "color": {
      "field": "title_type",
      "scale": {
        "domain": ["tv", "movie", "video", "videoGame"],
        "range": ["#9e9ac8", "#74c476", "#a6761d", "#6baed6"]
      },
      "legend": {
        "labelExpr": "datum.label == 'tv' ? 'Tv' : datum.label == 'movie' ? 'Movie' :datum.label == 'video' ? 'Video' : 'Video Game'"
      },
      "title": "Reference Type"
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM