I have two dataframes df1
and df2
as follows:
> 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
I want to plot these dataframes in just one diagram, split them to two different plots with same x
axis and add their names to the top left corner of their plots. Note that dateTime
is a POSIXct
object. Here is the code:
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"))
And the result is:
As you can see, X Data
and Y Data
are in the top left corner, but I really do not like to manually change the coordinates in geom_text
to get the exact position which I want. Is there a better way to do that without changing the coordinates manually?