【问题标题】:Multiple y-axes using plotly with data of different length多个 y 轴使用 plotly 和不同长度的数据
【发布时间】:2020-06-21 01:57:20
【问题描述】:

使用 plotly 我经常遇到多条线图和不同长度的数据的问题。然后我找到了this的解决方案:


library(plotly)

df1 <- data.frame(
  id = c("Honda", "Honda", "Honda", "Merc", "Merc", "Merc", "Toyota", "Toyota"),
  date = c('10/30/12', '10/31/12', '11/1/12', '11/2/12', '10/30/12', '10/31/12', '11/1/12', '11/3/12'),
  Value = c(2, 3, 3, 4, 1, 2, 3, 2)
)

df1$date <- as.Date(df1$date, "%m/%d/%y")

df1 %>%
  group_by(id) %>%
  plot_ly(x=~date, y=~Value, type='scatter', color=~id, mode="lines+markers") %>%
  layout(xaxis=list(title="Date"),yaxis=list(title="Cars Sold"))

现在我面临下一个问题。如何在此示例中添加多个 y 轴?是否还有可能使用 R 拥有 2 个以上的 y 轴并像页面底部的this Python 示例中那样左右排列它们?例如。左边是本田和奔驰,右边是丰田。我找到了解决方案here,但是数据的长度相同,所以这对我不起作用。

我想防止像在这个数据框中那样缩放具有不同数量级的数据:

df1 <- data.frame(
  id = c("Honda", "Honda", "Honda", "Merc", "Merc", "Merc", "Toyota", "Toyota"),
  date = c('10/30/12', '10/31/12', '11/1/12', '11/2/12', '10/30/12', '10/31/12', '11/1/12', '11/3/12'),
  Value = c(0.02, 0.03, 0.03, 4, 1, 2, 3, 2)
)

【问题讨论】:

    标签: r plot plotly yaxis


    【解决方案1】:

    请检查以下内容:

    library(plotly)
    
    df1 <- data.frame(
      id = c("Honda", "Honda", "Honda", "Merc", "Merc", "Merc", "Toyota", "Toyota"),
      yaxis = c("y", "y", "y", "y2", "y2", "y2", "y3", "y3"),
      date = c('10/30/12', '10/31/12', '11/1/12', '11/2/12', '10/30/12', '10/31/12', '11/1/12', '11/3/12'),
      Value = c(0.02, 0.03, 0.03, 4, 1, 2, 3, 2)
    )
    
    df1$date <- as.Date(df1$date, "%m/%d/%y")
    
    y2 <- list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "left",
      title = "Merc",
      position=0.1,
      showgrid = FALSE
    )
    
    y3 <- list(
      tickfont = list(color = "green"),
      overlaying = "y",
      side = "right",
      title = "Toyota",
      showgrid = FALSE
    )
    
    df1 %>%
      group_by(id) %>%
      plot_ly(x=~date, y=~Value, type='scatter', color=~id, mode="lines+markers", yaxis=~yaxis) %>%
      layout(xaxis=list(title="Date", domain = list(0.15, 0.95)), yaxis=list(title="Honda"), yaxis2=y2, yaxis3=y3)
    

    更多信息请见this

    【讨论】:

    • 谢谢!是否可以仅显示第一个数据集(-> Honda)中的网格以防止网格覆盖?
    • 当然,我相应地调整了代码。您应该尝试使用schema(),它可以让您浏览 plotly 的属性。
    猜你喜欢
    • 2020-07-19
    • 2022-07-06
    • 2015-06-09
    • 2021-03-10
    • 2018-04-08
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多