Ggplot折线图操作

时间:2017-10-25 10:41:00

标签: r ggplot2 dplyr tidyr tidyverse

我有以下数据并且想要绘制几个线ggplots(每个都代表不同的stock1。每个图将有多行代表因子1,2,3等(即第3到第6列)。

数据:

sample_data<-structure(list(Date = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L), .Label = c("2017-01-31", "2017-02-28", "2017-03-31", 
"2017-04-30"), class = "factor"), stock1 = structure(c(1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("a", "b", 
"c"), class = "factor"), Factor1 = c(5, 6, 8, 9, 5, 6, 7, 2, 
3, 4, 5, 6), Factor2 = c(4, 4.5, 5, 4, 4.5, 6, 2, 3.4, 4, 5, 
4, 3), Factor3 = c(6, 7.8, 8, 8.5, 9, 8.5, 4, 5, 6, 5, 5.5, 6
), Factor4 = c(5, 5.5, 6.2, 7, 5.5, 6, 3.4, 4, 5.6, 6, 7, 4)), .Names = c("Date", 
"stock1", "Factor1", "Factor2", "Factor3", "Factor4"), row.names = c(NA, 
-12L), class = "data.frame")

到目前为止,我已经尝试过:

ggplot(sample_data, aes(x=Date, y = [,3:6])) + geom_line() + facet_wrap(~Stock1)

2 个答案:

答案 0 :(得分:1)

我正在假设你想要如何呈现你的数据,并建议你开始这样做:

library(tidyverse)
sample_data %>% 
mutate(Date = as.Date(Date)) %>% 
gather("Factor", "Value", 3:6) %>% 
ggplot(aes(x = Date, y = Value, colour = Factor)) + 
geom_line() + 
facet_wrap(~stock1)

Output line plot

答案 1 :(得分:0)

library(tidyverse)
sample_data %>%
gather(key, value, c(Factor1:Factor4)) %>% 
ggplot(., aes(x = as.Date(Date), y = value, col = key)) + geom_line() + facet_wrap(~stock1)

这是你想要的吗?