如何调整ggplot代码,以便可以在一张图表上绘制3个或更多日期框架?

时间:2018-08-21 16:30:05

标签: r ggplot2 graph

我有3个数据帧,DF1,DF2和DF3。我想在一张图上绘制所有数据框。如何调整ggplot代码,以便可以在一张图表上绘制3个或更多日期框架?

Time1 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", 
"16:15:30"))

Measurement1 <- c("15", "18", "16", "17", "14", "15")

DF1 <- data.frame(Time1, Measurement1)

Time2 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", 
"16:15:30"))

Measurement2 <- c("20", "24", "27", "25", "26", "27")

DF2 <- data.frame(Time2, Measurement2)

Time3 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", 
"16:15:30"))

Measurement3 <- c("30", "32", "34", "31", "35", "33")

DF3 <- data.frame(Time3, Measurement3)

下面的ggplot代码;

Day1plot <- ggplot(DF1, aes(Time1, Measurement1, group = 1))+geom_point() +
geom_line() +
theme(plot.title = element_text(hjust = 0.5)) +
ggtitle('XD2 Consumption readings (Sun 3rd Of June 2018)') +
xlab('Times') +
ylab('kWh') + 
theme_bw() +
theme(plot.title = element_text(hjust = 0.5))

Day1plot + theme(axis.title.x = element_text(face="bold", colour="black", 
size=10),axis.text.x  = element_text(angle=90, vjust=0.5, size=10))

1 个答案:

答案 0 :(得分:2)

此解决方案结合了您的数据集并创建了一个数据集标识符列,因此您知道哪些行属于哪个数据集。另外,此标识符将用作绘图的分组变量:

示例数据

Time1 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", "16:15:30")
Measurement1 <- c("15", "18", "16", "17", "14", "15")
DF1 <- data.frame(Time1, Measurement1)

Time2 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", "16:15:30")
Measurement2 <- c("20", "24", "27", "25", "26", "27")
DF2 <- data.frame(Time2, Measurement2)

Time3 <- c("10:11:11", "11:30:30", "12:55:00", "14:35:30", "15:06:01", "16:15:30")
Measurement3 <- c("30", "32", "34", "31", "35", "33")
DF3 <- data.frame(Time3, Measurement3)

代码

library(tidyverse)

# update datasets in order to be able to be combined 
DF1 = DF1 %>% set_names("Time", "Measurement") %>% mutate(group = "DF1") 
DF2 = DF2 %>% set_names("Time", "Measurement") %>% mutate(group = "DF2") 
DF3 = DF3 %>% set_names("Time", "Measurement") %>% mutate(group = "DF3") 

# bind rows
DF = rbind(DF1, DF2, DF3)

# plot the big dataset using a grouping variable
ggplot(DF, aes(Time, Measurement, col = group, group = group))+
  geom_point() +
  geom_line() +
  theme(plot.title = element_text(hjust = 0.5)) +
  ggtitle('XD2 Consumption readings (Sun 3rd Of June 2018)') +
  xlab('Times') +
  ylab('kWh') + 
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))+ 
  theme(axis.title.x = element_text(face="bold", colour="black", 
                                    size=10),axis.text.x  = element_text(angle=90, vjust=0.5, size=10))

enter image description here