Search code examples
rggplot2plotlyr-plotlyggplotly

Showing a list of corresponding labels for ggplotly hover


I want to display information from a dataframe in an interactive box plot. The corresponding code is:

p=ggplot(data = data,
       aes(x = GeoAreaName,  fill= cat, text= Indicator)) +
  geom_bar()

ggplotly(p)

"cat" is a categorical variable describing data quality, "GeoAreaName" is a country name and "Indicator" is the data set name that "cat" describes.

The result I get is almost what I want: ggplotly result

However, I want to have the labels of the Indicator only shown when I hover above it, i.e. a list of names corresponding to the categories "cat" should appear, not every single one as its own segment in the bar plot.

Any suggestions?

Edit: Excerpt of the data: data


Solution

  • Aggregate the indicator by concatenation.

    dataNew <- data %>% 
        group_by(GeoAreaName, cat) %>%
        summarize(Indicator = paste(Indicator, collapse=", "), count=n())
    

    Plotting:

    p <- ggplot(data = dataNew, aes(x = GeoAreaName, y=count, fill= cat, text= Indicator)) + 
        geom_bar(stat="identity")