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
1.3k views
in Technique[技术] by (71.8m points)

ggplot2 - How to present scalable time data as a factor in the r ggplot package? (i.e. 1 hour, 5 hour, 10 hour)

I have groups of data at 0 hour, 3 hour, 12 hour, 24 hour, 48hour,... I want to graph that data so that the scale of the time is preserved.

runs <- c(1:25)
hours <- as.factor(c(0, 3, 12, 24, 48, 96))
treatments <- (c("a","b","c","d"))
things <- as.numeric(runif(600, min=1, max=15))
type <- expand.grid(hours,treatments,runs)
data.df <- data.frame(type,things)

names(data.df)[names(data.df)=="Var1"] <- "hour"
names(data.df)[names(data.df)=="Var2"] <- "treatments"

library(ggplot2)

ggplot(data.df, aes(x=as.factor(hour), y=things, fill=treatments)) +
   geom_boxplot() 

enter image description here

I need the data in the graph to be scaled, so the 3 hour tick is approx 1/4 of the distance to the 12 hour tick, and the 12 hour is half the distance to the 24 hour.

Using Stefan's answer we arrived at this plot: enter image description here

Using this code change

ggplot(data.df, aes(x = as.numeric(as.character(hours)), y=things, fill=things, group = hours))+
  geom_boxplot() +
  scale_x_continuous(breaks = as.numeric(as.character(hours)))

But unfortunately, I cannot change the group/fill to show the treatment.

Thank you!

question from:https://stackoverflow.com/questions/65865058/how-to-present-scalable-time-data-as-a-factor-in-the-r-ggplot-package-i-e-1-h

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

1 Reply

0 votes
by (71.8m points)

To achieve your desired result you could convert your hours variable to a numeric and map hours on the group aesthetic:

hours <- as.factor(c(0, 3, 12, 24, 48, 96))
things <- runif(36, min=1, max=10)
data.df <- data.frame(hours,things)

library(ggplot2)

ggplot(data.df, aes(x = as.numeric(as.character(hours)), y=things, fill=things, group = hours))+
  geom_boxplot() +
  scale_x_continuous(breaks = as.numeric(as.character(hours)))

EDIT For you updated question you could get the desired result by mapping both hour and treatment on the group aes using e.g interaction:

library(ggplot2)

ggplot(data.df, aes(x = as.numeric(as.character(hour)), y=things, fill=treatments, group = interaction(hour, treatments)))+
  geom_boxplot() +
  scale_x_continuous(breaks = as.numeric(as.character(hours)))


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

...