如何轻松绘制背景垂直条带?

How to easily plot background vertical bands?

在 Stata 中,我可以轻松地在背景中添加波段,例如预示经济衰退期:

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)

结果是一条带有背景垂直带的增加线:

在 Julia with Gadfly 中,我能找到的最好的是人为的:

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
)        

结果类似于Stata:

为了去除描边,我给主题一个returns透明白色的功能(如this thread中所建议)。我无法设置波段的填充,所以我将默认颜色设置为灰色并添加了一个虚拟字段 color 以将线图的颜色从灰色更改为另一种颜色。我还给出了数据的最大值和最小值的垂直带的y坐标,它可能与视口的最大值和最小值不重合。

有人知道更好的方法吗?

使用 Plots.jl 你可以只添加一个 vspan,例如:

vspan([1995, 1996], linecolor = :grey, fillcolor = :grey)
plot!(df[:year], df[:x])

这需要一项不平凡的工作。

你可以根据 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

GitHub issue 上的讨论之后,一位贡献者建议 Geom.rect,这需要为 y 轴添加最小值和最大值:

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")
          )
)