How to add fixed horizontal and vertical lines to a scatter plot in plotly

后端 未结 1 1338
清酒与你
清酒与你 2021-01-21 10:23

I have the following code producing a scatter plot and I would like to add both vertical and horizontal lines representing the mean values of the y axis and x axis, how could I

相关标签:
1条回答
  • 2021-01-21 11:01

    Using some random data for your df final. I don't know whether plotly provides some kind of geom_h/vline ... Instead I constructed the lines using dataframes which contain the start and the end point of the lines. Have a look:

    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
    

    0 讨论(0)
提交回复
热议问题