如何熔化数据框[重复项]

问题描述 投票:-2回答:2
我有一个数据帧,dratiodf

Date D10 D21 D63 D126 D252 2019-09-23 0.1557585 0.3977892 0.8583822 0.7153107 0.7517688 2019-09-24 0.1513844 0.2142586 0.7501128 0.6736790 0.7275896 2019-09-25 0.5314460 0.4254800 0.8604258 0.6612713 0.7469207 2019-09-26 0.5135381 0.4250006 0.9424716 0.7008503 0.7661933 2019-09-27 0.4816461 0.2371428 0.7969672 0.6351504 0.7307106 2019-09-30 0.6414031 0.3407633 0.8207621 0.6854996 0.7346074

我想做的是将各列融合在一起,得到一个看起来像这样的数据框:

Date: Type: Value: 2019-09-23 D10 0.1557585 2019-09-23 D21 0.3977892 2019-09-23 D63 0.8583822 2019-09-23 D126 0.7153107 2019-09-23 D252 0.7517688 2019-09-34 D10 0.1513844 2019-09-34 D21 0.2142586

我想要这个,这样我就可以按类型来刻画最终的情节,像这样:

ggplot(dratiodf, aes(x=Date, y=Value))+ geom_line()+ facet_wrap(.~type)+ theme_wsj()

我已经尝试过使用melt函数,但是我无法将其使用方法包起来。

而且,您能发现我的图形代码有什么问题吗,有些东西行不通?

r ggplot2 melt facet-wrap
2个回答
2
投票
我们可以使用gather

library(tidyr) library(dplyr) df1 %>% gather(Type, Value, -Date)

或使用pivot_longer(来自tidyr_1.0.0

df1 %>% pivot_longer(cols = - Date, names_to = "Type", values_to = "Value") # A tibble: 30 x 3 # Date Type Value # <chr> <chr> <dbl> # 1 2019-09-23 D10 0.156 # 2 2019-09-23 D21 0.398 # 3 2019-09-23 D63 0.858 # 4 2019-09-23 D126 0.715 # 5 2019-09-23 D252 0.752 # 6 2019-09-24 D10 0.151 # 7 2019-09-24 D21 0.214 # 8 2019-09-24 D63 0.750 # 9 2019-09-24 D126 0.674 #10 2019-09-24 D252 0.728 # … with 20 more rows

数据

df1 <- structure(list(Date = c("2019-09-23", "2019-09-24", "2019-09-25", "2019-09-26", "2019-09-27", "2019-09-30"), D10 = c(0.1557585, 0.1513844, 0.531446, 0.5135381, 0.4816461, 0.6414031), D21 = c(0.3977892, 0.2142586, 0.42548, 0.4250006, 0.2371428, 0.3407633), D63 = c(0.8583822, 0.7501128, 0.8604258, 0.9424716, 0.7969672, 0.8207621), D126 = c(0.7153107, 0.673679, 0.6612713, 0.7008503, 0.6351504, 0.6854996), D252 = c(0.7517688, 0.7275896, 0.7469207, 0.7661933, 0.7307106, 0.7346074)), class = "data.frame", row.names = c(NA, -6L))


1
投票
下次,提供像这样的可复制的数据帧。

df <- data.frame(Date = c("2019-09-23", "2019-09-24", "2019-09-25", "2019-09-26", "2019-09-27", "2019-09-30"), D10 = c(0.1557585, 0.1513844, 0.5314460, 0.5135381, 0.4816461, 0.6414031), D21 = c(0.3977892, 0.2142586, 0.4254800, 0.4250006, 0.2371428, 0.3407633), D63 = c(0.8583822, 0.7501128, 0.8604258, 0.9424716, 0.7969672, 0.8207621), D126 = c(0.7153107, 0.6736790, 0.6612713, 0.7008503, 0.6351504, 0.6854996), D252 = c(0.7517688, 0.727589, 0.7469207, 0.7661933, 0.7307106, 0.7346074))

这是您要使用melt函数的方式。

library(reshape2) dratiodf <- melt(df, id.vars = "Date", variable.name = "Type", value.name = "Value")

然后您的情节应适用于以下情况。

ggplot(dratiodf, aes(x = Date, y = Value, group = Type)) + geom_line() + facet_wrap(~ Type) + theme_wsj() + theme(axis.text.x = element_text(angle = 45, hjust = 1))

© www.soinside.com 2019 - 2024. All rights reserved.