【发布时间】:2019-05-30 21:27:32
【问题描述】:
我在尝试让我的 ggplot 上的 x 轴仅显示特定值时遇到问题。 X 轴是一个时间范围,但目前有很多时间无法读取(见图),理想情况下我希望每小时左右打一个勾,但我就是不知道怎么做。
任何建议都将不胜感激。
我已经尝试过针对类似问题的建议,但没有任何运气(请参阅下面我尝试过的大部分代码和错误)
这是我的图形代码;
ggplot(data, aes(x=time, y=binary)) +
geom_bar(stat='identity') +
facet_wrap(~id,scales="free_x", ncol=1,strip.position = "right")
这是我尝试解决问题的大部分内容;
scale_x_continuous(breaks=c(seq(16:00,17:00,18:00)))
>Error in seq.default(16:0, 17:0, 18:0, : 'from' must be of length 1 In addition: Warning message: In seq.default(16:0, 17:0, 18:0,) : extra arguments will be disregarded
scale_x_continuous(breaks=c(seq("16:00","17:00","18:00")))
> Error in seq.default("16:00", "17:00", "18:00") : 'from' must be a finite number In addition: Warning message: In seq.default("16:00", "17:00", "18:00") : NAs
强制引入
data$time <- gsub('\"', "", as.character(data$time), fixed=TRUE)
data$time <- as.Date(data$time, "%H-%M-%S")
> Warning messages: 1: In min(x) : no non-missing arguments to min; returning Inf 2: In max(x) : no non-missing arguments to max; returning -Inf 3: In min(diff(sort(x))) : no non-missing arguments to min; returning Inf 4: Removed 7290 rows containing missing values (position_stack).
x=data$time
as.numeric(gsub(",","",x,fixed=TRUE))
> Warning message: NAs introduced by coercion
scale_x_datetime(breaks = date_breaks("1 hour"), labels = date_format("%H:%M:%S"))
<ScaleContinuousDatetime>
Range:
Limits: 0 -- 1
这里是原始数据集的一个样本(因为它很大),很抱歉最初没有发布这个。 非常感谢您的帮助!
> data
time id binary
1 15:49 267 2
2 13:58 269 0
3 15:51 231 0
4 16:00 263 1
5 15:51 237 2
6 15:53 236 2
7 16:00 235 2
> dput(data)
structure(list(time = structure(c(2L, 1L, 3L, 5L, 3L, 4L, 5L), .Label = c("13:58",
"15:49", "15:51", "15:53", "16:00"), class = "factor"), id = c(267L,
269L, 231L, 263L, 237L, 236L, 235L), binary = c(2L, 0L, 0L, 1L,
2L, 2L, 2L)), .Names = c("time", "id", "binary"), class = "data.frame", row.names = c(NA,
-7L))
> str(data)
'data.frame': 7 obs. of 3 variables:
$ time : Factor w/ 5 levels "13:58","15:49",..: 2 1 3 5 3 4 5
$ id : int 267 269 231 263 237 236 235
$ binary: int 2 0 0 1 2 2 2
【问题讨论】:
-
您可以在问题中分享的最有帮助的是实际数据,通过
dput(data)或至少通过str(data)提供数据的实际结构。 (或一小部分数据的等价物) -
在 joran 的评论之后,您可以找到一些关于问题需要什么的见解,以便我们可以重现您的问题并为您提供答案,可以在这里找到how-to-make-a-great-r-reproducible-example
-
你想用
breaks=c(seq(16:00,17:00,18:00))做什么?这些将被读取为格式不正确的数字。通常seq接受 from、to 和 by 参数。