3

I have been using example on custom hover text (https://plot.ly/r/text-and-annotations/) to change hover text in barplots i'm working on. If my barplot only includes one stacked bar the new hover text doesn't show. Example (it's in the last plot where the hoverinfo is missing):

library(plotly) year <- c(2015,2015,2016,2016) type <- c('A','B','A','B') perc <- c(10,90,20,80) data <- data.frame(year,type,perc) # Plot all the data ... default hoverinfo shown plot_ly(data,x=~year,y=~perc,color=~type) %>% add_bars()%>% layout(barmode = "stack") # Plot all the data ... custom hoverinfo shown plot_ly(data,x=~year,y=~perc,color=~type, text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% add_bars()%>% layout(barmode = "stack") # Plot part of the data ... default hoverinfo shown plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type) %>% add_bars()%>% layout(barmode = "stack") # Plot part of the data ... custom hoverinfo does not appear! plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type, text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% add_bars()%>% layout(barmode = "stack") 

Using R version 3.3.2 and plotly version 4.5.6.

1 Answer 1

2

Got some help and the solution is to define the text as a list.

plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type, text = ~list(paste('Type',type,': ',perc,'%')),hoverinfo = 'text') %>% add_bars()%>% layout(barmode = "stack") 

This works as long as I know there is only one bar and the order of the ~type is the same throughout the dataset. If I change the types to

type <- c('A','B','B','A') 

and run

data <- data.frame(year,type,perc) plot_ly(data[data$year == 2016,],x=~year,y=~perc,color=~type, text = ~list(paste(year,'Type',type,': ',perc,'%')),hoverinfo = 'text') %>% add_bars()%>% layout(barmode = "stack") 

I don't get the right order of hoverinfo. So this is not the perfect solution.

Sign up to request clarification or add additional context in comments.

1 Comment

If one looks at the generated html file it looks like the x and y are arrays but the text is not an array (if you don't add the list command) when only one x. But why plotly doesn't generate the 'text' as an array in this case I don't know.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.