在y轴上方添加空间,而无需expand()

时间:2019-01-02 10:48:53

标签: r ggplot2 graph

当绘制百分比并且某列为100%时,值标签将从图形中删除。

enter image description here

对此有两种可能的解决方案:
1. scale_y_continuous(limits = c(0, 1.1)
2. scale_y_continuous(expand = c(0, 0, 0.2, 0)
但是,这两种解决方案都会扩大轴心。我宁愿只添加一个填充/边距,以免行长超过100%。这可能吗? enter image description here

工作示例

library(ggplot2)
library(magrittr)
data.frame("value" = c(0, 0.5, 1),
           "v1" = letters[1:3]) %>% 
        ggplot(aes(x = v1, 
                   y = value, 
                   label = value)) +
        geom_bar(stat = "identity") + 
        geom_text(stat = "identity",
                  vjust = -1) + 
        scale_y_continuous(breaks = seq(0, 1, 0.2), 
                           limits = c(0, 1),
                           labels = scales::percent, 
                           expand = c(0, 0, 0.2, 0)) + 
        theme_classic()

2 个答案:

答案 0 :(得分:4)

您可以在plot.margin函数中使用theme自变量填充图,并在coord_cartesian中关闭剪切,以使绘图不受约束到图面板。

data.frame("value" = c(0, 0.5, 1),
           "v1" = letters[1:3]) %>% 
  ggplot(aes(x = v1, 
             y = value, 
             label = value)) +
  geom_bar(stat = "identity") + 
  geom_text(stat = "identity",
            vjust = -1) + 
  scale_y_continuous(breaks = seq(0, 1, 0.2), 
                     limits = c(0, 1),
                     labels = scales::percent) + 
  theme_classic() +
  theme(plot.margin = margin(t = 10, unit = "pt")) + ## pad "t"op region of the plot
  coord_cartesian(clip = "off")

enter image description here

也许还值得注意的是,这仅是当您需要宽幅绘图时的一个问题。

答案 1 :(得分:2)

另一种方法是限制轴线的延伸。这是在软件包lemon中实现的,该软件包还允许您为每个刻度放置方括号,而不是为轴放置一行:

library(ggplot2)

df <- data.frame("value" = c(0, 0.5, 1),
           "v1" = letters[1:3])

p <- ggplot(df, aes(x = v1, 
                   y = value, 
                   label = value)) +
        geom_bar(stat = "identity") + 
        geom_text(stat = "identity",
                  vjust = -1) + 
        scale_y_continuous(breaks = seq(0, 1, 0.2), 
                           limits = c(0, 1),
                           labels = scales::percent,
                           expand = rep(0,4)) +
        theme_classic()

library(lemon)
p + coord_flex_cart(ylim=c(-0.01, 1.1), left=capped_vertical(capped='both', gap=0.0),
  bottom = brackets_horizontal())

enter image description here

可以使用参数lengthtick.length修改括号的长度。