在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)
在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为调整布局提供了统一的界面。
这里是下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...")