【问题标题】:Creating a line plot using plot_ly (R) with two y-axes使用带有两个 y 轴的 plot_ly (R) 创建线图
【发布时间】:2019-11-19 06:23:38
【问题描述】:

我是 plot_ly 包的新手,我正在尝试制作一个在 y 轴上有两个变量的时间序列线图。

在我的数据框“baro”中,我有 POSIXct 格式的“DateTime”变量,以及数字格式的“压力”和“温度”。

我的代码基于此处给出的示例:https://plot.ly/r/multiple-axes/

p <- plot_ly(baro)

add_trace(p, x = ~DateTime, y = ~Pressure, type = "scatter",
          mode = "lines", name = "Pressure")

add_trace(p, x = ~DateTime, y = ~Temperature, type = "scatter",
          mode = "lines", name = "Temperature", yaxis = "y2")

layout(p,
  title = "Pressure & Temperature", yaxis2 = ay,
  xaxis = list(title="x")
)

这会在 x 轴上输出一组标记为 -1 到 6 的轴,在 y 轴上输出标记为 -1 到 4 的一组坐标轴,并且没有绘制数据。

【问题讨论】:

  • 请分享dput(baro) 的输出,以便我们重现您的问题。
  • 函数之间应该有管道(“%>%”)。也许他们没有正确粘贴在您的问题中

标签: r r-plotly


【解决方案1】:

我更喜欢使用管道%&gt;% 而不是将对象归因于绘图。 当您有 2 个 Y 轴时,最好明确设置每个 Y 轴的布局。

这应该做你想做的:

# Build randon data
set.seed(123)

baro = data.frame(DateTime = as.POSIXct(1:10,origin = "2019-01-01"),
                  Pressure = sample(1000:2000,10),
                  Temperature = sample(20:60,10)
                  )

# Build plot

baro %>%
  plot_ly(type = "scatter", mode = "lines") %>%
  add_trace(x = ~DateTime, y = ~Pressure, name = "Pressure")%>%
  add_trace(x = ~DateTime, y = ~Temperature, name = "Temperature", yaxis = "y2") %>%
  layout(title = "Pressure & Temperature",
         yaxis = list(title = "Pressure"),
         yaxis2 = list(title = "Temperature",
                       overlaying = "y",
                       side = "right"
                       )
         )

这里是输出:

最好的问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多