【问题标题】:draw multiple lines for timeplot in R using ggplot使用 ggplot 在 R 中为时间图绘制多条线
【发布时间】:2019-06-15 01:00:30
【问题描述】:

我在 R 中有一个数据框。第一列是日期。其余列是每个类别的数据。

library(tidyverse)

mydf <- tribble(~Date, ~View1, ~View2, ~View3, ~View4, ~View5, ~View6,
        '2010-05-17', 13, 10, 13, 10, 13, 10,
        '2010-05-18', 11, 11, 13, 10, 13, 10,
        '2010-05-19',  4, 12, 13, 10, 13, 10,
        '2010-05-20',  2, 10, 13, 10, 13, 10,
        '2010-05-21', 23, 16, 13, 10, 13, 10,
        '2010-05-22', 26, 15, 13, 10, 13, 10
        )

如何用两条线绘制时间图?每列对应每一行。即 View1 一行,View2 一行,View3 一行,依此类推。 x 轴是日期。 ggplot中有没有可以轻松实现的功能?

我搜索了其他帖子,看到下面的解决方案,但它没有给我任何关于情节的信息。

mydf %>% 
  gather(key,value, View1, View2, View3, View4, View5, View6 )  %>% 
  ggplot(aes(x=Date, y=value, colour=key))

我也尝试了下面的命令。

test_data_long1 <- melt(mydf, id="Date") 
ggplot(data=test_data_long1,
       aes(x=date, y=value, colour=variable)) +
       geom_line()

它给了我一个错误。

Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error: All columns in a tibble must be 1d or 2d objects:
* Column `x` is function

【问题讨论】:

  • date 应该是Date
  • 第一次尝试缺少geom_line()

标签: r ggplot2


【解决方案1】:

几种方法...

library(dplyr)
library(ggplot2)

mydf %>% 
  mutate(Date = as.Date(Date)) %>% 
  ggplot(aes(x = Date)) +
  geom_line(aes(y = View1), colour = 'red') +
  geom_line(aes(y = View2), colour = 'blue')


mydf %>% 
  mutate(Date = as.Date(Date)) %>% 
  gather(-Date, key = 'View', value = 'value' )   %>% 
  ggplot(aes(x=Date, y=value, colour=View)) +
    geom_line()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2021-06-06
    • 2018-02-03
    • 2019-11-27
    • 2020-08-10
    相关资源
    最近更新 更多