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

Categories

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

r - ungroup data points with the same y value in ggplot2

I am trying to draw a bar graph to illustrate the trend when intervention attempts increase, Duration of sleep trend increase. enter image description here

Here's the graph I have. As you can see, ggplot2 has grouped all duration of sleep based on their intervention attempt (this would make the duration of sleep around 28 hours collectively, which is confusing). I was wondering if there's a way to somehow group the duration of sleep but make them spread out, instead of being on top of each other. enter image description here

#Data cleansing
library(tidyverse)
sleep_data <- read_csv("mock-data.csv")
sleep_data <- sleep_data[1:7,1:6]

library(hms)
library(lubridate) 

#Data Visualization
intervention_rating <- sleep_data$`Intervention rating`
intervention <- sleep_data$Intervention
bedtime <- sleep_data$Bedtime
wakeup_time <- sleep_data$`Wake up time`

sleepTime <- function(bed, wake){
  wake <- paste(Sys.Date(), wake)
  tmpbed <- paste(Sys.Date(), bed)
  d <- apply(data.frame(tmpbed, wake), 1, function(x) difftime(x[2], x[1], units = "hours"))
  adjust <- -(d < 0)
  tmpbed <- paste(Sys.Date() + adjust, bed)
  apply(data.frame(tmpbed, wake), 1, function(x) difftime(x[2], x[1], units = "hours"))
}

sleep_time_per_hour <- sleepTime(bedtime, wakeup_time) 
sleep_data <- sleep_data[1:7,1:7]
# 
ggplot(data = sleep_data, aes(y=sleep_time_per_hour, x=intervention)) +
        geom_bar(stat="identity") +
        theme_light() +
        ylim(c(0,50)) +
        xlab("Intervention Attempt") +
        ylab("Duration of Sleep") +
        geom_smooth(method = "lm")

question from:https://stackoverflow.com/questions/65623109/ungroup-data-points-with-the-same-y-value-in-ggplot2

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...