# Vegalite.jl; simple grouped bar chart

**URL:** <https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702>\
**Category:** Visualization\
**Created:** [December 25, 2019, 9:32pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702 "2019-12-25T21:32:26Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Usor](https://avatars.discourse-cdn.com/v4/letter/u/8dc957/32.png) [@Usor](https://discourse.julialang.org/u/Usor)\
**Post date:** [December 25, 2019, 9:32pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/1 "2019-12-25T21:32:26Z")

</div>

I’ve been fighting with this occasionally, and haven’t gotten it to work. I want to make a simple grouped bar chart out of a simple `DataFrame`, but no example I’ve seen that just quickly gets to the point.

Suppose it’s a simple one, having a few columns like `Year`, `AmountOfPeople` and `AmountOfPeopleCasualty`. You want to simply plot a bar chart where `x` has the year, and `y` has both the amount of people and the amount of casualties (out of these people), where these two columns are immediately next to each other per year.

---

<div class="post-metadata">

**Author:** ![davidanthoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/davidanthoff/32/223493_2.png) [@davidanthoff](https://discourse.julialang.org/u/davidanthoff)\
**Post date:** [December 25, 2019, 11:37pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/2 "2019-12-25T23:37:16Z")

</div>

[Here](https://www.queryverse.org/VegaLite.jl/stable/examples/examples_barchartshistograms/#Grouped-Bar-Chart-1) is an example of a grouped bar chart. Essentially you have to create a faceted figure currently.

I believe the vega-lite team is also working on something better, see [here](https://github.com/vega/vega-lite/issues/4703).

---

<div class="post-metadata">

**Author:** ![oheil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oheil/32/220745_2.png) [@oheil](https://discourse.julialang.org/u/oheil)\
**Post date:** [December 26, 2019, 9:22am UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/3 "2019-12-26T09:22:06Z")

</div>

A MWE according to the [example](https://www.queryverse.org/VegaLite.jl/stable/examples/examples_barchartshistograms/#Grouped-Bar-Chart-1)

```julia
julia> using DataFrames,VegaLite

julia> df=DataFrame(year=["90","91","92"],people=[10,12,14],cas=[5,6,7])
3×3 DataFrame
│ Row │ year │ people │ cas │
│ │ String │ Int64 │ Int64 │
├─────┼────────┼────────┼───────┤
│ 1 │ 90 │ 10 │ 5 │
│ 2 │ 91 │ 12 │ 6 │
│ 3 │ 92 │ 14 │ 7 │

julia> year=Array{String,1}()
0-element Array{String,1}

julia> name=Array{String,1}()
0-element Array{String,1}

julia> values=Array{Int,1}()
0-element Array{Int64,1}

julia> for index in 1:length(df.year)
           push!(year,df.year[index])
           push!(year,df.year[index])
           push!(name,"p")
           push!(name,"c")
           push!(values,df.people[index])
           push!(values,df.cas[index])
       end

julia> new_df=DataFrame(year=year,name=name,values=values)
6×3 DataFrame
│ Row │ year │ name │ values │
│ │ String │ String │ Int64 │
├─────┼────────┼────────┼────────┤
│ 1 │ 90 │ p │ 10 │
│ 2 │ 90 │ c │ 5 │
│ 3 │ 91 │ p │ 12 │
│ 4 │ 91 │ c │ 6 │
│ 5 │ 92 │ p │ 14 │
│ 6 │ 92 │ c │ 7 │

julia> new_df |> @vlplot(
                  :bar,
                  column={"year:o"},
                  y={"values", axis={grid=false} },
                  x={"name:n", axis={title=""} },
                  color={"name:n"},
                  spacing=0,
                  )

```

![visualization](https://global.discourse-cdn.com/julialang/original/3X/f/1/f1a7016f63d26f1fc2c284b1c6556a6c100e649a.png)

---

<div class="post-metadata">

**Author:** ![oheil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oheil/32/220745_2.png) [@oheil](https://discourse.julialang.org/u/oheil)\
**Post date:** [December 31, 2019, 2:35pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/4 "2019-12-31T14:35:15Z")

</div>

This example uses the support of Vega graphics in VegaLite.jl:

From the above example I have renamed the columns to make them more distinct from the keywords used in Vega (e.g. “values” and “value”).

This is the starting point from OPs example description:

```julia
using DataFrames,VegaLite
df=DataFrame(Year=["90","91","92"],AmountOfPeople=[10,12,14],AmountOfPeopleCasualty=[5,6,7])

julia> df
3×3 DataFrame
│ Row │ Year │ AmountOfPeople │ AmountOfPeopleCasualty │
│ │ String │ Int64 │ Int64 │
├─────┼────────┼────────────────┼────────────────────────┤
│ 1 │ 90 │ 10 │ 5 │
│ 2 │ 91 │ 12 │ 6 │
│ 3 │ 92 │ 14 │ 7 │

```

First we have to restructure the data:

```julia
Year=Array{String,1}()
AmountOf=Array{String,1}()
Amount=Array{Int,1}()
for index in 1:length(df.Year)
	push!(Year,df.Year[index])
	push!(Year,df.Year[index])
	push!(AmountOf,"People")
	push!(AmountOf,"PeopleCasualty")
	push!(Amount,df.AmountOfPeople[index])
	push!(Amount,df.AmountOfPeopleCasualty[index])
end
new_df=DataFrame(Year=Year,AmountOf=AmountOf,Amount=Amount)

julia> new_df
6×3 DataFrame
│ Row │ Year │ AmountOf │ Amount │
│ │ String │ String │ Int64 │
├─────┼────────┼────────────────┼────────┤
│ 1 │ 90 │ People │ 10 │
│ 2 │ 90 │ PeopleCasualty │ 5 │
│ 3 │ 91 │ People │ 12 │
│ 4 │ 91 │ PeopleCasualty │ 6 │
│ 5 │ 92 │ People │ 14 │
│ 6 │ 92 │ PeopleCasualty │ 7 │

```

Now we create the grouped bar chart using a Vega JSON string:

```julia
julia> vg"""{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 300,
  "height": 240,
  "padding": 5,

  "data": [
    {
      "name": "table"
    }
  ],

  "scales": [
    {
      "name": "xscale",
      "type": "band",
      "domain": {"data": "table", "field": "Year"},
      "range": "width",
      "padding": 0.2
    },
    {
      "name": "yscale",
      "type": "linear",
      "domain": {"data": "table", "field": "Amount"},
      "range": "height",
      "round": true,
      "zero": true,
      "nice": true
    },
    {
      "name": "color",
      "type": "ordinal",
      "domain": {"data": "table", "field": "AmountOf"},
      "range": {"scheme": "category20"}
    }
  ],

  "axes": [
    {"orient": "left", "scale": "yscale", "labelPadding": 4, "zindex": 1},
    {"orient": "bottom", "scale": "xscale"}
  ],

  "marks": [
    {
      "type": "group",

      "from": {
        "facet": {
          "data": "table",
          "name": "facet",
          "groupby": "Year"
        }
      },

      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "Year"}
        }
      },

      "signals": [
        {"name": "width", "update": "bandwidth('xscale')"}
      ],

      "scales": [
        {
          "name": "pos",
          "type": "band",
          "range": "width",
          "domain": {"data": "facet", "field": "AmountOf"}
        }
      ],

      "marks": [
        {
          "name": "bars",
          "from": {"data": "facet"},
          "type": "rect",
          "encode": {
            "enter": {
              "x": {"scale": "pos", "field": "AmountOf"},
              "width": {"scale": "pos", "band": 1},
              "y": {"scale": "yscale", "field": "Amount"},
              "y2": {"scale": "yscale", "value": 0},
              "fill": {"scale": "color", "field": "AmountOf"}
            }
          }
        },
        {
          "type": "text",
          "from": {"data": "bars"},
          "encode": {
            "enter": {
              "x": {"field": "x", "offset": {"field": "width", "mult": 0.5}},
              "y": {"field": "y", "offset": 8},
              "fill": [
                {"value": "black"}
              ],
              "align": {"value": "left"},
              "baseline": {"value": "middle"},
              "text": {"field": "datum.AmountOf"},
              "angle": {"value": 90}
            }
          }
        }
      ]
    }
  ]
}"""(new_df, "table")

```

![visualization](https://global.discourse-cdn.com/julialang/original/3X/c/9/c9ef58b5a631ceba83542c389f607d245e530240.png)  
The following documentations have been consulted:  
[https://www.queryverse.org/VegaLite.jl/stable/userguide/vega/](https://www.queryverse.org/VegaLite.jl/stable/userguide/vega/)

> **[Grouped Bar Chart Example](https://vega.github.io/vega/examples/grouped-bar-chart/)**
>
> Vega - A Visualization Grammar. Vega is a visualization grammar, a declarative format for creating, saving, and sharing interactive visualization designs. With Vega, you can describe the visual appearance and interactive behavior of a visualization...

> **[Stacked Bar Chart Example](https://vega.github.io/vega/examples/stacked-bar-chart/)**
>
> Vega - A Visualization Grammar. Vega is a visualization grammar, a declarative format for creating, saving, and sharing interactive visualization designs. With Vega, you can describe the visual appearance and interactive behavior of a visualization...

---

<div class="post-metadata">

**Author:** ![davidanthoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/davidanthoff/32/223493_2.png) [@davidanthoff](https://discourse.julialang.org/u/davidanthoff)\
**Post date:** [December 31, 2019, 5:32pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/5 "2019-12-31T17:32:08Z")

</div>

I just _yesterday_ merged a lot of new support for Vega specs! All of this is only available on `VegaLite#master`. In particular, there is now a `@vgplot` macro that works the same way as the `@vlplot` macro, just for Vega specs.The main benefit is that one doesn’t need to use these literal JSON strings anymore. The documentation for that new macro is [here](https://www.queryverse.org/VegaLite.jl/dev/userguide/vega/).The grouped bar chart example looks like [this](https://www.queryverse.org/VegaLite.jl/dev/examples/examples_vega_bar_charts/#Grouped-Bar-Chart-1) with the new syntax. The example is a little less nice than what @oheil posted because it has the data inline, instead of using a `DataFrame`. Would probably make sense to update the example in the docs to also use a `DataFrame` ([this](https://www.queryverse.org/VegaLite.jl/dev/userguide/vega/#Data-1) section in the docs exaplains how one passes external data to the `@vgplot` macro).

Oh, and one more small thing: try `stack(df, Not(:Year), variable_name=:AmountOf, value_name=:Amount)` for the `DataFrame` reshaping stuff 🙂

---

<div class="post-metadata">

**Author:** ![Usor](https://avatars.discourse-cdn.com/v4/letter/u/8dc957/32.png) [@Usor](https://discourse.julialang.org/u/Usor)\
**Post date:** [January 4, 2020, 2:00pm UTC](https://discourse.julialang.org/t/vegalite-jl-simple-grouped-bar-chart/32702/6 "2020-01-04T14:00:38Z")

</div>

Thanks, both.

It all looks very good. I hope to get at things soon.
