Home > other >  Custom interaction Plotly in ggplot - R
Custom interaction Plotly in ggplot - R

Time:05-16

I have a massive dataset that makes graph plotting tedious and complex.

Assume this simplified dataset:

library(data.table)
library(plotly)
library(ggplot2)
library(dplyr)

df <- data.table(continent = c(rep("America",3), rep("Europe",4)),
           state = c("USA", "Brazil", "Chile", "Italy", "Swiss", "Spain", "Greece"),
           X = rnorm(7, 5, 1),
           Y = rnorm(7, -13, 1),
)

df$X_sd = sd(df$X)
df$Y_sd = sd(df$Y)

Consider having > 30 levels for "state", which makes it very difficult to show them with different colours or shapes.

I have decided to use plotly to show this dataset.

Here what I have done:

p <- df %>%
  ggplot(aes(x=X,
              y=Y, 
              fill = continent,
              color = continent))  
  geom_errorbarh(aes(xmin = X - X_sd,
                     xmax = X   X_sd),
                 size = 0.5,
                 alpha = 0.3)  
  geom_errorbar(aes(ymin = Y - Y_sd,
                    ymax = Y   Y_sd),
                size = 0.5,
                alpha = 0.3)  
  geom_point(shape=21,
    color="black",
    size=3)  
  theme_bw()

ggplotly(p)

However, the interactive window does not show information regarding the country, which is what I want to achieve. In fact, every time I go over a point, I would like to have a window that shows: Continent, Country, X and Y (and in case I will have more factors or columns, I would like to be to include them too).

I have tried to add shape = country within the aesthetics, but 1) there are not enough shapes, 2) it fights against my decision of having shape = 21 for geom_point(), and 3) it adds a huge legend which I don't want.

How can I personalize the interaction window of plotly without adding extra and not-needed aesthetics?

Furthermore, I have tried to remove the legend by using:

guides(fill="none", color="none") 

or by

%>%  hide_legend()

but either way, do not work. How can I remove the legend?

CodePudding user response:

What you can do is add label in your aes to add factors like state. You can do that multiple times. You can use the following code:

p <- df %>%
  ggplot(aes(label = state,
             x=X,
             y=Y, 
             fill = continent))  
  geom_errorbarh(aes(xmin = X - X_sd,
                     xmax = X   X_sd),
                 size = 0.5,
                 alpha = 0.3)  
  geom_errorbar(aes(ymin = Y - Y_sd,
                    ymax = Y   Y_sd),
                size = 0.5,
                alpha = 0.3)  
  geom_point(shape=21,
             color="black",
             size=3)  
  theme_bw()  
  theme(legend.position = "none")

ggplotly(p)

Output:

enter image description here

  • Related