r - 如何在绘图中向散点图添加固定的水平线和垂直线

标签 r plotly r-plotly

我有以下代码生成散点图,我想添加代表 y 轴和 x 轴平均值的垂直线和水平线,我该怎么做?

 f <- list(
   family = "Courier New, monospace",
   size = 18,
   color = "#7f7f7f"
  )
 x <- list(
   title = "Age of Buildings",
   titlefont = f,
   zeroline = FALSE,
   showline = FALSE,
   showticklabels = TRUE,
   showgrid = TRUE
  )
  y <- list(
    title = "Total Violations",
    titlefont = f,
    zeroline = FALSE,
    showline = FALSE,
    showticklabels = TRUE,
    showgrid = TRUE
   )
fig2 <- plot_ly(final, x=~agebuilding, y=~violationstotal, mode= "markers", color = ~INdexrehabless6, size = ~totalvalue)
fig2 <- fig2 %>% layout(xaxis = x, yaxis = y, legend=list(title=list(text='<b> Housing Conditions </b>'))) #chaging name legend
fig2

这是我得到的 plotly

enter image description here

最佳答案

为你的 df final 使用一些随机数据。我不知道 plotly 是否提供某种 geom_h/vline ...相反,我使用包含线条起点和终点的数据帧构建了线条。看看:

set.seed(50)
final <- data.frame(
  agebuilding = 150 * runif(50), 
  violationstotal = 30 * runif(50),
  INdexrehabless6 = factor(sample(0:1, 50, replace = TRUE)),
  totalvalue = 100 * runif(50)
)

mean_x <- data.frame(x = rep(mean(final$agebuilding), 2), y = c(0, ceiling(10* max(final$violationstotal))/10))
mean_y <- data.frame(y = rep(mean(final$violationstotal), 2), x = c(0, ceiling(10* max(final$agebuilding))/10))

library(plotly)
fig2 <- plot_ly(final) %>%
  add_markers(x=~agebuilding, y=~violationstotal, color = ~INdexrehabless6, size = ~totalvalue) %>% 
  add_lines(x = ~x, y = ~y, data = mean_x, name = "Mean x") %>% 
  add_lines(x = ~x, y = ~y, data = mean_y, name = "Mean y")
fig2 <- fig2 %>% layout(xaxis = x, yaxis = y, legend=list(title=list(text='<b> Housing Conditions </b>'))) #chaging name legend
fig2

enter image description here

关于r - 如何在绘图中向散点图添加固定的水平线和垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61210547/

相关文章:

python - 将线型映射到python中具有多个子图的绘图图中的数据

javascript - 如何删除plotly.js 图表轴中的非整数?

R查找数据框中某些列与另一列匹配的行

r - 如何找到至少2个向量中常见的元素?

r - dyShading R dygraph

r - 如何在ggplot的条形图中更改x轴文本的位置?

d3.js - 当两个条的值为 0 时,相对 barmode 标签中的 Plotly.js 会重叠

r - 线条下方的3D填充

r - 在 plotly::subplot 中显示所有 plotly 标题

javascript - 如何更新 R Shiny 中的绘图小部件的显示/隐藏痕迹以响应操作按钮而不重新渲染