1 year ago
#388340
SqueakyBeak
Combining two data frames in single ggplot with facet wrap with different factor names?
Say I have a df1 (incidents) and a df2 (records).
df1 <- data.frame(date = c("2021-07-01","2021-07-09","2021-07-04","2021-07-05"), value = c(200, 250, 123, 400), machine=c('abc1', 'abc2', 'abc3', 'abc4'),sprocket=c('boop', 'blip', 'blip', 'boop'))
df2 <- data.frame(date2 = c("2021-07-02","2021-07-03","2021-07-06","2021-07-08"), record=c('record1', 'record2', 'record3', 'record4'), robot = c('abc2', 'abc42', 'abc1', 'abc3'))
So I want to plot x = date and y = value by sprocket for df1. Then for df2, I want to OVERLAY the records by machine, regardless of sprocket, on the correct date and machine.
Im having trouble getting the machines to line up without renaming 'robot' to 'machine' for df2, but I feel like there should be a way of specifying 'robot' = 'machine' or something in the facet_wrap.
Here is more of what I'm actually working with:
p3 <-ggplot() +
geom_point(df1, mapping = aes(x = date, y = value, color = value> 1.5 | value< -1.5)) +
scale_colour_manual(values = c("black", "red")) +
facet_wrap(vars(machine),ncol=5)+
facet_grid(sprocket~ machine) +
geom_hline(yintercept = 1.5, linetype = "dashed",color = "red")+
geom_hline(yintercept = -1.5, linetype = "dashed",color = "red")+
theme_classic() +
ylim(-30, 30)+
scale_x_date(breaks = seq(as.Date("2021-07-01"), max(df1$date), by="3 months"), date_labels = "%b") +
xlab("1974") +
ylab("% blahblah")+
#here's the records bit
geom_segment(df2, mapping = aes(x=date2, xend=date2, y=-30, yend=30), linetype = 'dashed') +
geom_point()+
facet_wrap(.~robot, ncol=5)
What I want to do is plot df2 on top of the existing df2 graph seamlessly without renaming variables. I was able to do this mostly by renaming 'robot' to 'machine' for df2 but I want to know how to do it without that. Im still missing retaining the sprocket facet_grid part:
r
dataframe
ggplot2
facet-wrap
facet-grid
0 Answers
Your Answer