Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

ggplot2 - R ggplot actuals and multiple simulated points in same plot with legend

How can I draw a ggplot for simulated predictions and their means with actual points?

For month 1 to 9, one point of the actual(df) is assigned, and month 10 and 11, simulated 5 points and mean point need to be plotted with a legend

#actual
month<-1:9
df<-c(0.20, 0.342, 0.710, 0.228, 0.124, 0.203, 0.956, 0.593, 0.195)
actual<-data.frame(month, df)


#simPred for month 10:11
sim1<-c(0.182, 0.235)
sim2<-c(0.165, 0.233)
sim3<-c(0.174, 0.258)
sim4<-c(0.139, 0.393)
sim5<-c(0.201, 0.412)
simPred<-data.frame(sim1, sim2,sim3,sim4,sim5)%>% 
  add_column(month=seq(from=length(month)+1, to=length(month)+nrow(simPred), by=1), Means=rowMeans(simPred[, 1:5]))                                                     

#combined
melted<-merge(actual, simPred, all=TRUE, by="month")
> melted
   month    df  sim1  sim2  sim3  sim4  sim5  Means
1      1 0.200    NA    NA    NA    NA    NA     NA
2      2 0.342    NA    NA    NA    NA    NA     NA
3      3 0.710    NA    NA    NA    NA    NA     NA
4      4 0.228    NA    NA    NA    NA    NA     NA
5      5 0.124    NA    NA    NA    NA    NA     NA
6      6 0.203    NA    NA    NA    NA    NA     NA
7      7 0.956    NA    NA    NA    NA    NA     NA
8      8 0.593    NA    NA    NA    NA    NA     NA
9      9 0.195    NA    NA    NA    NA    NA     NA
10    10    NA 0.182 0.165 0.174 0.139 0.201 0.1722
11    11    NA 0.235 0.233 0.258 0.393 0.412 0.3062                                                
question from:https://stackoverflow.com/questions/65894299/r-ggplot-actuals-and-multiple-simulated-points-in-same-plot-with-legend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How's this look? We can pivot your data into long format and then merge it.

library(tidyverse)
month<-1:9
df<-c(0.20, 0.342, 0.710, 0.228, 0.124, 0.203, 0.956, 0.593, 0.195)
actual<-data.frame(month, df)

#simPred for month 10:11
sim1<-c(0.182, 0.235)
sim2<-c(0.165, 0.233)
sim3<-c(0.174, 0.258)
sim4<-c(0.139, 0.393)
sim5<-c(0.201, 0.412)
simPred<-data.frame(sim1, sim2,sim3,sim4,sim5) %>% 
  mutate(month=c(10, 11)) %>%
  pivot_longer(names_to = "sim", cols=starts_with("sim"), values_to="df") %>%
  select(-sim) %>%
  rbind(actual)

ggplot(simPred, aes(x=month, y=df)) +
  geom_point() +
  stat_summary(fun.data = "mean_cl_boot", color="red")

plot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...