r - 如何在ggplot2

时间:2018-05-04 09:10:43

标签: r ggplot2

我想在ggplot2中增加面板背景的大小,以便扩展到轴标题,如下图所示:

Graph of GDP

我尝试使用element_rect,但没有成功。这是我到现在为止所得到的。

dat <- data.frame(x=2001:2017, y=rnorm(17,100))
ggplot2::ggplot(data=dat, ggplot2::aes(x=x, y=y)) +
ggplot2::geom_line(size=1.5)  + 
ggplot2::theme(panel.background=ggplot2::element_rect(fill="darkgrey"), 
plot.background=ggplot2::element_rect(fill="lightgrey", color=NA)) + 
ggplot2::ggtitle("Title of the plot") 

My Version

任何帮助将不胜感激!

由于

丹尼尔

1 个答案:

答案 0 :(得分:1)

你可以尝试

# first plot
p <- ggplot(data=dat, aes(x=x, y=y)) +
           geom_line(size=1.5)  + 
           theme(panel.background=element_rect(fill="darkgrey"),
                 plot.background=element_rect(fill="darkgrey"))
# blank plot
p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_blank() + 
      theme(plot.background=element_rect(fill="lightgrey"),
            line = element_blank(), 
            axis.text =  element_blank(),
            axis.title = element_blank(),
            plot.title = element_text(hjust = 0))

# plot with title
p2 <- p1 + ggtitle("Title of the plot", subtitle = "this is a sub") 
# plot with figure text
p3 <- p1 + ggtitle("",subtitle = "this is a second sub") 

# final plot
library(cowplot)
plot_grid(p2, p, p3,  nrow = 3, rel_heights = c(10, 80, 10))

enter image description here