R boxplot looks strange with text as tooltip

32 Views Asked by At

I need to create a SINGLE boxplot object in order to print it with plot function (no need to have tooltip) or to print it with ggplotly with tooltip custom information. This is for a Shiny App.

Here is the code to prepare data :

library(tidyverse)
library(plotly)
library(gapminder)

europe <- gapminder %>% filter(continent=="Europe") %>% select(country, year, lifeExp)
europe <- pivot_wider(europe, names_from = year, values_from = lifeExp)
position <- c("south", "west","west","south","east","east", "east", "north", "north", "west", "west", "south", "east", "north", "north", "west", "south", "west", "north", "east", "south", "east", "east", "east", "east", "south", "north", "west", "south", "north")
annotation <- europe %>% select(country)
annotation["position"] <- position

cl <- "country"
year <- "1997"

myyear <- europe %>% select(country, year) %>% merge(., annotation, by="country")

Then the code to create the boxplot object :

myboxplot <- ggplot(myyear, aes(x=position, y=.data[[year]])) +
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(aes(color=.data[[cl]]), shape=16, position=position_jitter(0.2), size=2)

plot(myboxplot)
ggplotly(myboxplot)

As you can test, the plot function plot the boxplot in a good way and the ggplotly function too.

Now I want to add a custom text in the ggplotly tooltip so I modify the boxplot building as this :

myboxplot <- ggplot(myyear, aes(x=position, y=.data[[year]], text=paste("life exp:",.data[[year]]))) + 
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(aes(color=.data[[cl]]), shape=16, position=position_jitter(0.2), size=2)

plot(myboxplot)
ggplotly(myboxplot)

The plot function gives a strange boxplot ! But the ggplotly function gives a fine boxplot with the good tooltip text.

Why plot function has this strange look in that case ?

How to deal with it ?

I really need to construct a single object and I cant modify it after it's building because I store it in a list in order to use it later in my Shiny App.

Any clue ? Thanx

1

There are 1 best solutions below

1
AudioBubble On

Adding the label to the data frame seems to work fine:

# changes here
colnames(myyear)[2] <- 'exp'
myyear <- myyear %>% mutate(year = year, label=paste('life exp:',exp))

myboxplot <- ggplot(myyear, aes(x=position, y=exp)) + 
  geom_boxplot(outlier.shape = NA) +
  geom_text(aes(label=label)) + 
  geom_jitter(aes(color=.data[[cl]]),shape=16,position=position_jitter(0.2), size=2)

plot(myboxplot)
ggplotly(myboxplot)

You'll have to adjust the placement to suit.

enter image description here