1

I'm trying to add one point to the already built plotly figure, and highlight this point on the graph. so for instance, I want to add the point (x=0.3, y=4) and locate it on the plot

Here is the code

#function of H0

h=function(pl,u,g){
sigma=sqrt(2)*qnorm((1+g)/2)
x=pl/u
h=pnorm(((log(x)/sigma) + (sigma/2)))
return(h)
}

#fill in matrix

pl=1.5
u=seq(1.5,9,0.1)
g=seq(.2,.7,0.1)
M=matrix(0,nrow=length(u),ncol=length(g))

for(i in 1:length(u)) {
for(j in 1:length(g)) {
M[i,j]=h(pl,u[i],g[j])
}
}

rownames(M)=u
colnames(M)=g


#plot

library(plotly)

fig <- plot_ly(
  type = 'contour',
  y = u/pl,  
  x = g,
  z = M,
  colorscale = 'Jet',
  autocontour = F,
  contours = list(
    start = 0.2,
    end = 0.8,
    size = 0.1,
    showlabels=TRUE
    )
  )%>%
  layout(title = 'Heacount Index', xaxis = list(title = 'Gini index'), 
         yaxis = list(title = 'Mean/Poverty Line (u/z)'))


  fig 
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78

1 Answers1

0

You can use add_trace for this:

# function of H0
h=function(pl,u,g){
  sigma=sqrt(2)*qnorm((1+g)/2)
  x=pl/u
  h=pnorm(((log(x)/sigma) + (sigma/2)))
  return(h)
}

# fill in matrix
pl=1.5
u=seq(1.5,9,0.1)
g=seq(.2,.7,0.1)
M=matrix(0,nrow=length(u),ncol=length(g))

for(i in 1:length(u)) {
  for(j in 1:length(g)) {
    M[i,j]=h(pl,u[i],g[j])
  }
}

rownames(M)=u
colnames(M)=g


# plot
library(plotly)

fig <- plot_ly(
  type = 'contour',
  y = u/pl,  
  x = g,
  z = M,
  colorscale = 'Jet',
  autocontour = F,
  contours = list(
    start = 0.2,
    end = 0.8,
    size = 0.1,
    showlabels=TRUE
  )
)%>%
  layout(title = 'Heacount Index', xaxis = list(title = 'Gini index'), 
         yaxis = list(title = 'Mean/Poverty Line (u/z)'))


fig <- add_trace(fig, x = 0.3, y = 4, type = "scatter", mode = "markers", color = I("red"), inherit = FALSE, name = "myPoint")
fig

result

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
  • Thank You a lot !! Can I add a customized text for this point? So when you hover the mouse over the point, it will display Country X? Another question, Can I add vertical lines or circles if I'm willing to divide the chart into zones? – Jinane Jouni Nov 03 '21 at 09:20
  • Regarding the hoverinfo please check [this](https://plotly.com/r/hover-text-and-formatting/). For vertical lines [this](https://stackoverflow.com/questions/34093169/horizontal-vertical-line-in-plotly) and for circles take a look [here](https://plotly.com/r/shapes/). – ismirsehregal Nov 03 '21 at 10:46