我有一个R数据结构,其在numerical
字段中融合后具有char
个值和value
个日期。
我正在考虑如何在Date
融化后管理变量ggplot
。
在绘图之前,我不想将数据结构dat.m
或molten
中的日期列表分开。
variable = Date
(此处称为dates
)的输出应用于参数scale_x_discrete("Date", labels = dates)
或dat.m
?预期输出:x轴上的日期为Date
的刻面图,以及图1中y轴中Date
中的molten$value
以外的其他值
图。 1 x轴上的日期Date
的预期输出(对不起,此处部分截止日期)
输出的代码如下
dat.m <- structure(list(REM = c(160, 150), kevyt = c(380, 420), syva = c(110, 180), Date = c("1.1.2011", "2.2.2012")), .Names = c("REM", "kevyt", "syva", "Date"), class = "data.frame", row.names = c(NA, -2L))
library("data.table")
str(dat.m)
print(dat.m)
molten <- melt(as.data.table(dat.m, keep.rownames = "Vars"), id.vars = "Vars") # https://stackoverflow.com/a/44128640/54964
print("Hello 2")
str(molten)
print(molten)
# TODO take dates from molten[, "Date"]. Here or somehow inside ggplot? Pseudocodes:
# dates <- molten[, "Date"] ...
# OR
# somehow directly in ggplot
library("ggplot2")
p <- ggplot(molten, aes(x = Vars, y = value, fill=variable)) +
geom_bar(stat='identity')
输出
'data.frame': 2 obs. of 4 variables:
$ REM : num 160 150
$ kevyt: num 380 420
$ syva : num 110 180
$ Date : chr "1.1.2011" "2.2.2012"
REM kevyt syva Date
1 160 380 110 1.1.2011
2 150 420 180 2.2.2012
Warning message:
In melt.data.table(as.data.table(dat.m, keep.rownames = "Vars"), :
'measure.vars' [REM, kevyt, syva, Date] are not all of the same type. By order of hierarchy, the molten data value column will be of type 'character'. All measure variables not of type 'character' will be coerced to. Check DETAILS in ?melt.data.table for more on coercion.
[1] "Hello 2"
Classes ‘data.table’ and 'data.frame': 8 obs. of 3 variables:
$ Vars : chr "1" "2" "1" "2" ...
$ variable: Factor w/ 4 levels "REM","kevyt",..: 1 1 2 2 3 3 4 4
$ value : chr "160" "150" "380" "420" ...
- attr(*, ".internal.selfref")=<externalptr>
Vars variable value
1: 1 REM 160
2: 2 REM 150
3: 1 kevyt 380
4: 2 kevyt 420
5: 1 syva 110
6: 2 syva 180
7: 1 Date 1.1.2011
8: 2 Date 2.2.2012
我不能简单地执行线程R: ggplot display all dates on x axis的提议,因为molten
不仅包含整数,还包含character
个日期。伪代码基于线程直接使用dat.m
# https://stackoverflow.com/a/41856325/54964
ggplot(data = dat.m) +
geom_point(mapping = aes(x = Date, y = value, fill = variable)) +
geom_bar(stat='identity') +
scale_x_date(date_labels="%s", Dates) # TODO problem here
有关其余代码,请参阅第(2)点。
R:3.4.0(backports)
操作系统:Debian 8.7