R语言 线上方的值以Plotly表示

1l5u6lss  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(186)

我正在尝试用Plotly绘制一个面积图。下面你可以看到我的代码

library(plotly)

density <- density(diamonds$carat)

fig <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'tozeroy')
fig <- fig %>% layout(xaxis = list(title = 'Carat'),
         yaxis = list(title = 'Density'))

fig

现在我想在这一行的顶部显示值。我尝试了这几行代码:

fig <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'tozeroy',
               text = ~paste0(" ",round(density$y,0)),
               textposition = "outside"
               
               )
fig <- fig %>% layout(xaxis = list(title = 'Carat'),
                      yaxis = list(title = 'Density'))

fig

这段代码没有产生我所期望的结果,所以有人能帮助我如何修复这个问题并查看行上方的值吗?

velaa5lx

velaa5lx1#

要使标签显示在图表中,请将text添加到mode。不幸的是,即使在尝试了textposition的不同选项后,我也无法将标签放置在线条的“顶部”。

library(plotly)

density <- density(diamonds$carat)

fig <- plot_ly(
  x = ~ density$x, y = ~ density$y, type = "scatter", fill = "tozeroy",
  mode = "text+lines", text = ~ paste0(" ", round(density$y, 0)),
  textposition="outside"
)

fig <- fig %>% layout(
  xaxis = list(title = "Carat"),
  yaxis = list(title = "Density")
)

fig

相关问题