如何在R中图的左上角添加图名称?

时间:2019-06-12 08:13:36

标签: r ggplot2 geom-text

我有两个数据帧df1df2,如下所示:

> df1
             dateTime value
1 2018-06-27 00:00:01     6
2 2018-06-27 00:00:02     2
3 2018-06-27 00:00:03     3
4 2018-06-27 00:00:04     1
> df2
             dateTime value
1 2018-06-27 00:00:01     3
2 2018-06-27 00:00:02     8
3 2018-06-27 00:00:03     4
4 2018-06-27 00:00:04     5

我只想在一张图中绘制这些数据框,将它们分成具有相同x轴的两个不同的图,然后将其名称添加到其图的左上角。请注意,dateTimePOSIXct对象。这是代码:

library(grid)
library(dplyr)

plot1 <- df1 %>%
  select(dateTime, value) %>%
  ggplot() +
  geom_point(data = df1, aes(dateTime, value)) +
  geom_line(data = df1, aes(x = dateTime, y = value), color = 'green') +
  geom_text(aes(x = df1$dateTime[1], y = df1$value[1], label = "X Data"), color = "red", size = 7) +
  theme(axis.text=element_text(size = 14), axis.title=element_text(size = 14),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

plot2 <- df2 %>%
  select(dateTime, value) %>%
  ggplot() +
  geom_point(data = df2, aes(dateTime, value)) + 
  geom_line(data = df2, aes(x = dateTime, y = value), color = 'red') +
  xlab("dateTime") +
  geom_text(aes(x = df2$dateTime[1], y = df2$value[1]+5, label = "Y Data"), color = "green", size = 7) +
  theme(axis.text=element_text(size = 14), axis.title=element_text(size = 14))

grid.newpage()
grid.draw(rbind(ggplotGrob(plot1), ggplotGrob(plot2), size = "last"))

结果是:

enter image description here

如您所见,X DataY Data位于左上角,但我真的不喜欢手动更改geom_text中的坐标来获取我所要的确切位置想。有没有一种更好的方法,而无需手动更改坐标?

1 个答案:

答案 0 :(得分:0)

我已使用?annotate完成此操作。这是一个简单的示例:

library(ggplot2)
library(scales)
library(grid)

y <- c(6,2,3,1)
x <-  as.POSIXct(c('00:00:01', '00:00:02', '00:00:03', '00:00:04'), format = '%H:%M:%S')
df1 <- data.frame(x, y)

y2 <- c(3,8,4,2)
x2 <-  as.POSIXct(c('00:00:01', '00:00:02', '00:00:03', '00:00:04'), format = '%H:%M:%S')
df2 <- data.frame(cbind(x2, y2))

plot1 <- ggplot() + geom_point(data = df1, aes(x, y)) + 
scale_x_time(labels=time_format('%H:%M:%S', tz=Sys.timezone())) + 
annotate('text', label='first graph', x=-Inf, y=Inf, hjust=0, vjust=1)

plot2 <- ggplot() + geom_point(data = df2, aes(x2, y2)) + 
scale_x_time(labels=time_format('%H:%M:%S',  tz=Sys.timezone())) + 
annotate('text', label='second graph', x=-Inf, y=Inf, hjust=0, vjust=1)

grid.newpage()
grid.draw(rbind(ggplotGrob(plot1), ggplotGrob(plot2), size = "last"))

result graph