Как добавить название графика в верхнем левом углу графика в R? - PullRequest
0 голосов
/ 12 июня 2019

У меня есть два кадра данных df1 и df2 следующим образом:

> 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 идобавьте их имена в верхний левый угол их графиков.Обратите внимание, что dateTime является POSIXct объектом.Вот код:

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 Data и Y Data находятся в верхнем левом углу, но я действительно не люблю вручную изменять координаты в geom_text, чтобы получить точное положение, которое я хочу.Есть ли лучший способ сделать это без изменения координат вручную?

1 Ответ

0 голосов
/ 12 июня 2019

Я использовал ?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

...