如何使ggplot冠军窗口,而不是情节格?(How to align ggplot title wi

2019-06-25 10:10发布

ggplot2版本0.9的情节标题的对齐的行为改变。 而在v0.8.9取向是相对于绘图窗口,在V0.9的排列是相对于绘图网格。

现在,而我大部分同意,这是可取的行为,我常常有很长的情节标题。

问:是否有与绘图窗口,而不是情节网格对齐情节标题的方法吗?

我在寻找的,因为该地块的自动对齐的解决方案。 换句话说,手动对齐使用hjust不会为我工作(我在数百个小区的每个项目运行此)。

任何使用的溶液grid直接也是可接受的。


一些示例代码和情节:(注意标题如何得到在窗口右侧截断)。

dat <- data.frame(
  text = c(
    "It made me feel very positive to brand X", 
    "It was clear and easy to understand",
    "I didn't like it al all"),
  value=runif(3)
)
library(ggplot2)
ggplot(dat, aes(text, value)) + 
  geom_bar(stat="identity") +
  coord_flip() +
  opts(title="Thinking about the ad that you've just seen, do you agree with the following statements? I agree that...") +
  theme_bw(16)

Answer 1:

在GGPLOT2 0.9,你可以很容易地改变布局。

p <- ggplot(dat, aes(text, value)) + 
  geom_bar(stat="identity") +
  coord_flip() +
  opts(title="Thinking about the ad that you've just seen,\ndo you agree with the following statements?\nI agree that...") +
  theme_bw(16)

gt <- ggplot_gtable(ggplot_build(p))
gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(1, max(gt$layout$r))
grid::grid.draw(gt)

也许,在未来的版本中,将GGPLOT2为调整布局提供了统一的界面。



Answer 2:

这里是下GGPLOT2 2.2.1的解决方案。 函数安排在ggplot的顶部中心的标题文字对象。

library(gridExtra)

# A function that puts a title text object centered above a ggplot object "p"
add_centered_title <- function(p, text){
    grid.arrange(p, ncol = 1, top = text)
}

# Create the chart from your sample data
 test_chart <- ggplot(dat, aes(text, value)) + 
  geom_bar(stat="identity") +
  coord_flip() +
  theme_bw(16)

# Usage:
add_centered_title(test_chart,
                   "Thinking about the ad that you've just seen, do you agree with the following statements? I agree that...")

# Or you can pipe a ggplot into this function using the %>% dplyr pipe:
library(dplyr)
test_chart %>%
  add_centered_title("Thinking about the ad that you've just seen, do you agree with the following statements? I agree that...")


文章来源: How to align ggplot title with window rather than plot grid?
标签: r ggplot2