12

ggplot20.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)

在此处输入图像描述

4

2 回答 2

14

在 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 将提供一致的界面来调整布局。

在此处输入图像描述

于 2012-06-11T08:05:42.397 回答
1

这是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...")
于 2017-10-06T13:57:11.060 回答