结合使用geom_boxplot和scale_x_datetime [英] combined use of geom_boxplot and scale_x_datetime

查看:209
本文介绍了结合使用geom_boxplot和scale_x_datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 geom_boxplot ,并同时使用 scale_x_datetime 重新调整轴。然而 geom_boxplot 需要因子作为输入,而 scale_x_datetime 将只接受类 POSIXct
这里有一个可重复的例子:

pre $ library $ g


日期<-c(02/27/92,02/27/92)
次< -c(20:03:20,22:29:56)
x< - paste(日期,时间)
x< - strptime(x,%m /%d /%y%H:%M:%S)
test = cbind (测试)= c(a,b)
plot1 = ggplot(测试)+ geom_boxplot(aes(aes).frame(rep(x,20)),rnorm(40) x = factor(a),y = b))
plot1
plot2 = plot1 + scale_x_datetime(breaks = date_breaks(1 hour))
plot2

plot1会很好,但最后一行会给我带来错误:

 错误:输入无效:time_trans只能用于POSIXct类的对象

然而,对于 geom_boxplot ,如果x值不是一个因素,它将执行一个不希望的结果:

  ggplot(test)+ geom_boxplot(aes(x = a,y = b))

有什么想法?

编辑:



预期结果:我只想第一次使用标签(格式为%H%M),第二个时间点没有标签。

解决方案

这似乎按我的预期工作。 (您从未说过您的预期。)

  plot2 = plot1 + scale_x_discrete(labels = format.Date(x,% Y /%m /%d%H))
plot2

您通过使用: aes(x = factor(a),y = b)创建了一个x因子变量,因此任何标签格式都需要考虑x-变量。我不使用ggplot2,因为它广泛的非标准评估和代码隐藏驱使我疯了,但是我确实想到了R对象的基本模式和类。


I want to use geom_boxplot and rescale my axis with scale_x_datetime at the same time. However geom_boxplot requires a factor as an input, while scale_x_datetime will only accept class POSIXct. Here is a reproducible example:

library(ggplot2)
library(scales)
dates <- c("02/27/92", "02/27/92")
times <- c("20:03:20", "22:29:56")
x <- paste(dates, times)
x <- strptime(x, "%m/%d/%y %H:%M:%S")
test = cbind(data.frame(rep(x, 20)), rnorm(40))
names(test)=c("a", "b")
plot1 = ggplot(test) + geom_boxplot(aes(x=factor(a), y=b))
plot1
plot2 = plot1 + scale_x_datetime(breaks = date_breaks("1 hour"))
plot2

plot1 will be fine but the last line casts me the error:

Error: Invalid input: time_trans works with objects of class POSIXct only

however that is not an option for geom_boxplot which will execute with an undesired result if the x-value is not a factor:

ggplot(test) + geom_boxplot(aes(x=a, y=b))

Any ideas?

EDIT:

Desired result: I want to have a label for the first time only (in the format e.g. "%H%M") and no label for the second point in time.

解决方案

This seems to work as I expected. (You never did say how you expected.)

plot2 = plot1 + scale_x_discrete(labels=format.Date(x, "%Y/%m/%d %H"))
plot2

The point here is that you created an x-factor variable by using: aes(x=factor(a), y=b) so any label formatting needs to respect the mode of the x-variable. I don't use ggplot2 because its widespread non-standard evaluation and code hiding drives me nuts, but I do think in terms of the basic modes and classes of R objects.

这篇关于结合使用geom_boxplot和scale_x_datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆