我正在尝试使用ggplot
来绘制以下日期框架中包含的数据:
df <- data.frame( dress_id = c(1,2,3,4,5),
29/8/2013 = c(2000,150,6,1000,900),
31/8/2013 = c(2000,200,7,1100,1000),
2/9/2013 = c(2400,600,7,1350,1300),
4/9/2013 = c(2600,600,7,1500,1400),
style = c("Sexy", "Casual","vintage","Brief","cute"))
我想以x轴作为日期(29/8/2013 ... 2/9/2013),以y轴作为日期的销售价格,最后是我的风格。
使用ggplot可以吗?
答案 0 :(得分:1)
这是zx8754答案的详细信息。
首先,请注意,我在日期列的前面放置了X
:这是因为R中的列名不应以数字开头。
df <- data.frame( dress_id = c(1,2,3,4,5),
"X29/8/2013" = c(2000,150,6,1000,900),
"X31/8/2013" = c(2000,200,7,1100,1000),
"X2/9/2013" = c(2400,600,7,1350,1300),
"X4/9/2013" = c(2600,600,7,1500,1400),
style = c("Sexy", "Casual","vintage","Brief","cute"))
接下来,我加载tidyverse
软件包,该软件包包含用于处理data.frames的函数,还包括ggplot2
library(tidyverse)
最后,我将您的数据从宽转换为长:这是通过gather
函数完成的。结果,data.frame中现在有一个日期列,其中包含所有当前日期,而值列中包含销售价格。
df %>%
gather(date, value, -dress_id, -style) %>%
mutate(date = as.Date(date, format = c("X%d.%m.%Y"))) %>%
ggplot(aes(x = date, y = value, colour = style)) +
geom_line()