r - 使用 R plotly 使所有刻度出现在轴上

标签 r graph plotly r-plotly

我编写了一个代码,使用我的数据制作带有散点图的子图。这是一个图表:

enter image description here

这是 x 轴上的小时数。如您所见,并非所有这些都出现在 x 轴上。我怎样才能让所有 24 小时都在轴上?即使例如在数据框中没有 23 点钟的值,我也希望它位于 x 轴上。如何做到这一点?

这是我的代码:

plot <- function(df) {

  subplotList <- list()
  for(metric in unique(df$metrics)){
    subplotList[[metric]] <- df[df$metrics == metric,] %>%
      plot_ly(
        x = ~ hr,
        y = ~ actual,
        name = ~ paste(metrics, " - ", time_pos),
        colors = ~ time_pos,
        hoverinfo = "text",
        hovertemplate = paste(
          "<b>%{text}</b><br>",
          "%{xaxis.title.text}: %{x:+.1f}<br>",
          "%{yaxis.title.text}: %{y:+.1f}<br>",
          "<extra></extra>"
        ),
        type = "scatter",
        mode = "lines+markers",
        marker = list(
          size = 7,
          color = "white",
          line = list(width = 1.5)
        ),
        width = 700,
        height = 620
      ) %>% layout(autosize = T,legend = list(font = list(size = 8)))
  }
  subplot(subplotList, nrows = length(subplotList), margin = 0.05)
}

最佳答案

这可以通过 xaxis 属性在 layout 中实现,就像这样。可以通过 tickvals 设置刻度或中断,通过 ticktext 设置刻度标签。

在下面的可重现示例中使用一些随机数据对此进行了说明:

library(plotly)

set.seed(42)

d <- data.frame(
  x = sort(sample(24, 15)),
  y = 1:15 + runif(15),
  z = 1:15 + runif(15)
)

plot_ly(d) %>%
  add_trace(x = ~x, y = ~y, type = "scatter", mode = "lines+markers") %>% 
  add_trace(x = ~x, y = ~z, type = "scatter", mode = "lines+markers") %>% 
  layout(xaxis = list(tickvals = 1:24, ticktext = paste0(1:24, "h")))

enter image description here

关于r - 使用 R plotly 使所有刻度出现在轴上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63572370/

相关文章:

r - 无法让年份因子指向 x 轴

r - R:删除字符变量的多个空列

python - Matplotlib 直方图,频率为千

java - 如何使用 JFreeChart 固定自动范围避免负值

python - plotly :类型错误:无法将字典更新序列元素#0 转换为序列

r - 根据 dplyr 中的组 var 计算时间戳之间的时间量

r - 提取黄土局部多项式函数中的拟合项(在 R 中)(不是 Predict())

javascript - Highcharts:动态(以编程方式)分配轴名称

python - plotly 基本示例显示 jupyter 实验室中没有 plotly

python - 使用 Pandas 数据框绘制 Holoviews.Image