1

In Stata I can easily add bands in the background, e.g. to signal a period of recession:

clear
set obs 2
gen year = 1990
replace year = 2000 if _n == 2
gen x = 0
replace x = 1 if _n == 2

twoway ///
    (scatteri 1 `=' 1995 1 `=' 1996, bcolor(gs10) recast(area) lwidth(none)) ///
    (line x year)

The result is an increasing line with a background vertical band:

Background vertical bands in Stata

In Julia with Gadfly, the best I could find was contrived:

using Gadfly, DataFrames, Colors

df = DataFrame(year = [1990; 2000], x = [0; 1], color = [1; 1])

x_shade = [1995 1995 1996 1996]
y_shade = [0 1 1 0]

theme = Theme(
    discrete_highlight_color = u -> ARGB(1, 1, 1, 0),
    default_color = colorant"grey")

p = plot(
    layer(
        x = x_shade,
        y = y_shade,
        Geom.polygon(preserve_order = true, fill = true),
        order = 1
    ),
    layer(df,
          y = "x",
          x = "year",
          color = "color",
          Geom.line,
          order = 2
          ),
    theme
)        

The result is similar to Stata:

Background vertical bands in Julia with Gadfly

To remove the stroke, I gave the theme a function that returns a transparent white (as suggested in this thread). I was unable to set the fill of the band, so I set the default color to grey and added a dummy field color to change the color of the line plot from grey to another color. I also gave the y-coordinates of the vertical band from the maximum and minimum of the data, which may not coincide with the maximum and minimum of the viewport.

Does someone know of a better way?

miguelmorin
  • 5,025
  • 4
  • 29
  • 64

3 Answers3

2

With Plots.jl you can just add a vspan, e.g.:

vspan([1995, 1996], linecolor = :grey, fillcolor = :grey)
plot!(df[:year], df[:x])
miguelmorin
  • 5,025
  • 4
  • 29
  • 64
Michael K. Borregaard
  • 7,864
  • 1
  • 28
  • 35
0

This would require a non-trivial work.

You can base off Geom.vline, where you would need to create something like VBandGeometry (like VLineGeometry), and specify how to build the band (like render(::VLineGeometry)), getting the limits correctly at Compose

Felipe Lema
  • 2,700
  • 12
  • 19
0

Following the discussion on the GitHub issue, one contributor suggested Geom.rect, which requires adding a minimum and a maximum for the y axis:

using Gadfly, DataFrames

df = DataFrame(year = [1990; 2000], x = [0; 1], color = [1; 1])

recessions = DataFrame(peaks = [1995],
                       troughs = [1996],
                       ymin = minimum(df[:x]),
                       ymax = maximum(df[:x]))

plot(
    recessions,
    xmin = :peaks,
    xmax = :troughs,
    ymin = :ymin,
    ymax = :ymax,
    Geom.rect,
    Theme(default_color = colorant"grey"),
    layer(df,
          y = "x",
          x = "year",
          Geom.line,
          order = 2,
          Theme(default_color = colorant"black")
          )
)
miguelmorin
  • 5,025
  • 4
  • 29
  • 64