如何将平均值线添加到散点图为r的散点图中

问题描述 投票:1回答:1

我有下面的代码生成散点图,我想同时添加代表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

这是我得到的情节

enter image description here

r plotly r-plotly
1个回答
0
投票

为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

© www.soinside.com 2019 - 2024. All rights reserved.