【问题标题】:How to plot a discontinue line in R如何在R中绘制中断线
【发布时间】:2021-12-09 04:24:30
【问题描述】:

我想按城市绘制一条连续线,也就是说我只想连接日期相互跟随的点。

代码:

city = c(rep("paris", 4), rep("lyon", 11), rep("marseille", 10), rep("lille", 5), rep("toulouse", 4), rep("bordeaux", 3))

start = c("2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-30", "2018-07-31", "2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-07-29", "2018-07-30", "2018-07-31", "2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-03", "2018-08-04", "2018-08-05")

max = c(rep(36.4, 4), rep(37.2,3), rep(38.4,8), rep(37.4,10), rep(36.7,5), rep(34.9,4), rep(34.8,3))


tab = as.data.frame(city, start, max)
tab$max = as.numeric(tab$max)
tab$start = as.Date(tab$start)

fig <- plot_ly(tab, x = ~start, y = ~max, color = ~city, mode = 'marker')

fig

我在不想连接的地方放了一个十字架

【问题讨论】:

    标签: r r-plotly


    【解决方案1】:

    使用dplyrggplot2

    数据:

    city <- c(rep("paris", 4), rep("lyon", 11), rep("marseille", 10), rep("lille", 5), rep("toulouse", 4), rep("bordeaux", 3))
    
    start <- c("2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-30", "2018-07-31", "2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-07-29", "2018-07-30", "2018-07-31", "2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-03", "2018-08-04", "2018-08-05")
    
    value <- c(rep(36.4, 4), rep(37.2,3), rep(38.4,8), rep(37.4,10), rep(36.7,5), rep(34.9,4), rep(34.8,3))
    
    
    tab <- data.frame(city, start, value)
    

    代码:

    df <- tab %>% 
      group_by(city) %>% 
      mutate(start = as.Date(start)) %>%
      mutate(temp = ifelse(start + 1 == lead(start),1,0)) %>%
      filter(temp == 0)
    
    tab2 <- tab %>% 
      mutate(start = as.Date(start)) %>%
      mutate(group = ifelse(start > df$start & city == df$city,paste(city,'0'),paste(city,"1")))
    

    图表:

    ggplot(tab2,
           aes(x = start, y = value,
               group = group, colour = city)) +
      geom_line() +
      geom_point()
    

    附带说明,不要使用已经存在的函数(例如 max 用于您的变量)

    【讨论】:

    • 这对我不起作用。我总是有连接两点的线。但是我有这个消息:较长对象的大小不是较短对象大小的倍数
    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2021-07-05
    • 2015-09-25
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多