Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Answer

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)))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...