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

时间:2018-06-27 09:43:25

标签: julia gadfly

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

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

Background vertical bands in Stata

在朱莉娅(Julia)和牛d(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:

Background vertical bands in Julia with Gadfly

要删除笔划,我给主题提供了一个函数,该函数返回透明的白色(如this thread中所建议)。我无法设置色带的填充度,因此我将默认颜色设置为灰色,并添加了一个虚拟字段color来将线条图的颜色从灰色更改为另一种颜色。我还从数据的最大值和最小值给出了垂直带的y坐标,这可能与视口的最大值和最小值不一致。

有人知道更好的方法吗?

3 个答案:

答案 0 :(得分:0)

使用Plots.jl,您只需添加一个vspan,例如:

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

答案 1 :(得分:0)

这将需要不平凡的工作。

您可以以Geom.vline为基础,在那里您需要创建类似VBandGeometry(例如VLineGeometry)的东西,并指定如何构建乐队(例如render(::VLineGeometry)) ,在Compose

正确获取限制

答案 2 :(得分:0)

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