Лучший способ разбить данные на несколько строк? - PullRequest
0 голосов
/ 27 октября 2019

У меня есть данные, как показано: 2021 43466,822 средний вариант

2021 43510,982 высокий вариант

2021 43416,407 низкий вариант

2021 43468,429 постоянная фертильность

2021Мгновенная замена 43580,45

И нужно получить диаграмму: https://image.prntscr.com/image/eBKqmOUsSa_6PBlomh5Erg.png

Я пробовал вариант сгиба трансформации, но он мне не помогает. И сделать для этого много слоев - будет много кода. Есть ли какой-нибудь умный способ? Также мне понадобится легенда, подобная показанной.

    vegalite({
      height:300,
      autosize: "fit",
      width:width,
      title: {text:"Ukraine Population Prospects",
              subtitle:"Total population, million"
             },
      data: {
              url:"https://gist.githubusercontent.com/turiy/005f2ce11637fefcde8e9d6efdb0c2e6/raw/19e67bb3a6d63e7fd9f49a596e5d24404469bd63/population_prospects.csv"},
      transform: [{"calculate": "datum.population/1000", "as": "population"},{fold:["medium variant","high variant", "low variant", "constant fertility","instant replacement", "momentum", "zero migration", "constant mortality", "no change"]}],
      layer: [
        { mark: "line",
          encoding:{      
            "x": {
              "timeUnit": "utcyear",
              "field": "year",
              "type": "temporal",
              "axis": {
                "values":[1950,1991,2020,2100],
                "domain": false,
                "gridDash": {"value": [1,1]}
              }
            },
            "y": {
              "field": "population",
              "type": "quantitative",
              "scale": {"domain": [15,55]},
              "axis": {
                "domain": false ,
                "gridDash": {"value": [1,1]}
              }
            }
          },
          color: {"value":"#0000ff"},
          transform:[{filter:{"timeUnit": "utcyear", "field": "year", "range": [1950, 2020]}}]
        },
        {
          mark: "line",legend:{title:"low variant"},
          encoding:{      
            x: {
              "timeUnit": "utcyear",
              "field": "year",
              "type": "temporal",
              "axis": {
                "values":[1950,1991,2020,2100],
                "domain": false,
                "gridDash": {"value": [1,1]}}
            },
            y: {
              "field": "population",
              "type": "quantitative",
              "scale": {"domain": [15,55]},
              "axis": {
                "domain": false ,
                "gridDash": {"value": [1,1]}
              }
            },
            legends:{
              "orient": "top-right",
              "stroke": "color",
              "title": "Origin",
              "encode": {
             "symbols": {
              "update": {
                "fill": {"value": ""},
                "strokeWidth": {"value": 2},
                "size": {"value": 64}
              }
            }
          }
            },
            color: {"field": "key", "type":"nominal"}

          },    
          transform:[{filter:{"timeUnit": "year", "field": "year", "range": [2020, 2100]}},
                     {filter:{field:"type", "equal":"low variant"}}]
         }


      ]})

И я получаю вот так https://image.prntscr.com/image/3Y9WNk4SQzGYWDr2JKWV9A.png

1 Ответ

0 голосов
/ 27 октября 2019

Если ваши варианты перечислены по имени в столбце, как в вашем примере набора данных, вы можете использовать кодировку деталей, чтобы разбить их на разные строки ( ссылка редактора vega ):

{
  "data": {
    "url": "https://gist.githubusercontent.com/turiy/005f2ce11637fefcde8e9d6efdb0c2e6/raw/19e67bb3a6d63e7fd9f49a596e5d24404469bd63/population_prospects.csv"
  },
  "mark": "line",
  "encoding": {
    "detail": {"type": "nominal", "field": "type"},
    "x": {"type": "quantitative", "field": "year"},
    "y": {"type": "quantitative", "field": "population"}
  }
}

enter image description here

Если вы используете color вместо detail, каждая строка будет другого цвета, и будет добавлена ​​легенда.

Комудобавить метки в правой части диаграммы, вы можете использовать текстовую метку с агрегированным преобразованием;как то так:

{
  "data": {
    "url": "https://gist.githubusercontent.com/turiy/005f2ce11637fefcde8e9d6efdb0c2e6/raw/19e67bb3a6d63e7fd9f49a596e5d24404469bd63/population_prospects.csv"
  },
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "detail": {"type": "nominal", "field": "type"},
        "x": {"type": "quantitative", "field": "year"},
        "y": {"type": "quantitative", "field": "population"}
      }
    },
    {
      "transform": [
        {"filter": "datum.type != 'estimate'"},
        {
          "aggregate": [{"op": "argmax", "field": "year", "as": "rightmost"}],
          "groupby": ["type"]
        }
      ],
      "mark": {"type": "text", "align": "left"},
      "encoding": {
        "text": {"type": "nominal", "field": "rightmost.type"},
        "x": {"type": "quantitative", "field": "rightmost.year"},
        "y": {"type": "quantitative", "field": "rightmost.population"}
      }
    }
  ],
  "width": 400
}

enter image description here

...