代码之家  ›  专栏  ›  技术社区  ›  MelBourbon

不能使用element\u line更改线型

  •  1
  • MelBourbon  · 技术社区  · 7 年前

    我想用以下数据创建一个图作为示例:

    library(data.table)
    library(ggplot2)
    library(plotly)
    
    Data <- data.table(Datum = c("2017-11-01","2017-11-02","2017-11-03","2017-11-04","2017-11-05","2017-11-06","2017-11-07","2017-11-08","2017-11-09","2017-11-10"),Index = c(200,250,230,210,190,215,216,250,260,245), Long = c(c(250,220,225,215,240,255,256,266,223,222)))
    Data$Datum <- as.Date(Data$Datum, format = "%Y-%m-%d")
    
    startdate <- min(Data$Datum)
    enddate <- max(Data$Datum)
    
    plot <- ggplot(Data, aes(Datum)) +
      geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) + 
      geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) + 
      theme(panel.background = element_rect(fill = "white")) +
      theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(size = 0.5, colour = "grey", linetype = "dotted")) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
      scale_y_continuous(breaks=seq(0,300,20)) + 
      scale_x_date(breaks = seq(as.Date(startdate), as.Date(enddate), by="2 month"), date_labels = "%m %Y") +
      ylab("") +
      xlab("")
    
    
    plot <- ggplotly(plot)
    print(plot)
    

    chart

    但正如您在图中所看到的,即使设置为 linetype = "dotted"

    如何更改线型或我的方法有什么问题?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Michael Harper    7 年前

    从您的代码中可以看出,在ggplot中,绘图按需要显示,但一旦转换为plotly,就会丢失虚线。如评论中所述,这似乎是一个限制 plotly . 然而,这是一种可以使用的变通方法。

    因为ggplotly函数可以从 geom_line 函数,一种简单的修复方法是删除Y线,只需添加一些手动指定的水平线,如下所示使用 geom_hline 功能:

    plot <- ggplot(Data, aes(Datum)) +
      geom_hline(yintercept =c(200, 220, 240, 260), size = 0.5, colour = "grey", linetype = "dotted") +
      geom_line(aes(y = Index, colour = "Index"), size = 0.5, alpha = 0.5) + 
      geom_line(aes(y = Long, colour = "Long"), size = 0.5, alpha = 0.5) + 
      scale_y_continuous(breaks=seq(0,300,20)) + 
      ylab("") +
      xlab("") +
      theme(panel.background = element_rect(fill = "white"),
            panel.grid.major.x = element_blank(),
            panel.grid.major.y = element_blank())
    
    plot <- ggplotly(plot)
    print(plot)
    

    enter image description here

    退房 here 有关geom_线函数的更多文档。

    不需要手动指定步骤,您可以通过查找最大和最小y值,然后创建序列来添加以自动确定行距:

    min.plot <- roundUP(min(Data$Index,Data$Long),10) - 20
    max.plot <- max(Data$Index,Data$Long) + 20
    y.axis <- seq(from = min.plot, to = max.plot, by = 10)
    

    并编辑 geom_hline 参数:

    geom_hline(yintercept = y.axis, size = 0.5, colour = "grey", linetype = "dotted")