具有不同y轴标签的R ggplot facet_wrap,一个值,一个百分比

时间:2018-12-07 22:26:46

标签: r ggplot2 time-series visualization facet-wrap

我正在ggplot中使用.lists-wrapper { display: flex; justify-content: space-between; flex-wrap: wrap; .list { width: 20%; } h4 { margin-bottom: 22px; } ul { display: flex; flex-direction: column; flex-wrap: wrap; margin-bottom: 35px; margin-left: -5px; } } 绘制时间序列值及其百分比:

对于下面的图,上图是值,下图是百分比变化。我希望下图中的y轴为“%”。通常在ggplot中,我会做类似

的操作
facet_wrap

但是,由于我使用的是facet_wrap,我如何指定我只希望2个图的y轴标签之一为百分比?

enter image description here

P.S。这是生成该图的代码:

+ scale_y_continuous(labels = scales::percent)

1 个答案:

答案 0 :(得分:1)

我同意以上观点,即切面实际上不适合此用例。对齐单独的地块是正统的做法。

也就是说,如果您已经有一堆格式良好的ggplot对象,并且确实不想仅重构轴标签的代码,则可以将它们转换为grob对象并在内部进行挖掘:

library(grid)

# Convert from ggplot object to grob object
gp <- ggplotGrob(out_gg)

# Optional: Plot out the grob version to verify that nothing has changed (yet)
grid.draw(gp)

# Also optional: Examine the underlying grob structure to figure out which grob name 
# corresponds to the appropriate y-axis label. In this case, it's "axis-l-2-1": axis 
# to the left of plot panels, 2nd row / 1st column of the facet matrix.
gp[["layout"]]
gtable::gtable_show_layout(gp)

# Some of gp's grobs only generate their contents at drawing time.
# Using grid.force replaces such grobs with their drawing time content (if you check 
# your global environment, the size of gp should increase significantly after running 
# the grid.force line).
# This step is necesary in order to use gPath() to generate the path to nested grobs 
# (& the text grob for y-axis labels is nested rather deeply inside the rabbit hole).
gp <- grid.force(gp)
path.to.label <- gPath("axis-l-2", "axis", "axis", "GRID.text")

# Get original label
old.label <- getGrob(gTree = gp,
                     gPath = path.to.label,
                     grep = TRUE)[["label"]]

# Edit label values
new.label <- percent(as.numeric(old.label))

# Overwrite ggplot grob, replacing old label with new
gp = editGrob(grob = gp,
              gPath = path.to.label,
              label = new.label,
              grep = TRUE)

# plot
grid.draw(gp)

modified grob