简体   繁体   English

如何在 r ggplot package 中将可缩放时间数据作为一个因素呈现? (即 1 小时、5 小时、10 小时)

[英]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.我有 0 小时、3 小时、12 小时、24 小时、48 小时……的数据组,我想绘制这些数据的图表,以便保留时间的比例。

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

在此处输入图像描述

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.我需要对图表中的数据进行缩放,因此 3 小时刻度大约是到 12 小时刻度距离的 1/4,而 12 小时是到 24 小时距离的一半。

Using Stefan's answer we arrived at this plot:使用 Stefan 的回答,我们得到了这个 plot: 在此处输入图像描述

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!谢谢!

To achieve your desired result you could convert your hours variable to a numeric and map hours on the group aesthetic:为了达到您想要的结果,您可以将您的hours变量转换为数字和 map hoursgroup美学:

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 eg interaction :编辑对于您更新的问题,您可以通过使用例如interactiongroup aes 上映射hourtreatment来获得所需的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM