Home > front end >  r plot binary and numerical variables in same plot
r plot binary and numerical variables in same plot

Time:07-06

I am looking to plot binary variable and numerical variable in the same plot. I have tried but the y axis seems to just be the Binary scale. enter image description here

My data is a larger dataset of the excerpt below

dat <- structure(list(timestamp = c("29-06-2021-06:00", "29-06-2021-06:01", 
"29-06-2021-06:02", "29-06-2021-06:03", "29-06-2021-06:04", "29-06-2021-06:05", 
"29-06-2021-06:06", "29-06-2021-06:07", "29-06-2021-06:08", "29-06-2021-06:09", 
"29-06-2021-06:10", "29-06-2021-06:11", "29-06-2021-06:12", "29-06-2021-06:13", 
"29-06-2021-06:14", "29-06-2021-06:15", "29-06-2021-06:16", "29-06-2021-06:17", 
"29-06-2021-06:18", "29-06-2021-06:19", "29-06-2021-06:20", "29-06-2021-06:21", 
"29-06-2021-06:22", "29-06-2021-06:23", "29-06-2021-06:24", "29-06-2021-06:25", 
"29-06-2021-06:26"), SID = c(301L, 351L, 304L, 357L, 358L, 302L, 
303L, 309L, 356L, 304L, 308L, 351L, 304L, 357L, 358L, 302L, 303L, 
352L, 307L, 353L, 304L, 308L, 352L, 307L, 304L, 354L, 356L), 
    Tor = c(0.70161919, 0.639416295, 0.288282073, 0.932362166, 
    0.368616626, 0.42175565, 0.409735918, 0.942170196, 0.381396521, 
    0.818102394, 0.659391671, 0.246387978, 0.196001777, 0.632630259, 
    0.66618385, 0.440625167, 0.639759498, 0.050001835, 0.775660271, 
    0.762934189, 0.516830196, 0.244674975, 0.38620466, 0.970792903, 
    0.752674581, 0.190366737, 0.56596405), Lowt = c(0L, 0L, 1L, 
    0L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 
    0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L), Hit = c(1L, 0L, 0L, 
    1L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-27L))
ggplot(new_1, aes(x=Timestamp))   
  geom_line(aes(y=SID))  
  geom_point(aes(y=Lowt))

CodePudding user response:

using the dataset you provide :

library(ggplot2)
ggplot(dat, aes(x=timestamp))   
  geom_line(aes(y=Tor,group=1),col="red") 
  geom_point(aes(y=Lowt),col="blue") 
  theme(axis.text.x =element_text(angle=90))

enter image description here

CodePudding user response:

It is maybe not completely what you want, but you can make a "conditional density plot" using cdplot. These plots provide an overview of how a categorical variable (Lowt and Hit) change across various levels of a continuous variable (SID). First you need to modify you data a bit where the Lowt and Hit will be combined to one column called presence using pivot_longer. After that you can plot it like this:

library(dplyr)
library(tidyr)
new_dat <- pivot_longer(dat, cols = Lowt:Hit, values_to = 'presence') %>%
  select(presence, SID)
  
cdplot(factor(new_dat$presence) ~ new_dat$SID,
       xlab = "SID",
       ylab = "presence")

Output:

enter image description here

  • Related