Home > Software engineering >  How do I create plots using geom_violin, geom_jitter and plotly?
How do I create plots using geom_violin, geom_jitter and plotly?

Time:10-14

I am creating plot using geom_violin() and geom_jitter(). Everything works find using ggplot, however once I include plotly, I loose the violin shape. See below -

Plot with only ggplot - enter image description here

Plot with plotly - enter image description here

Can anyone help me understand what I'm doing wrong and how to fix. See reproducible code below -

# libraries
library(tidyverse)
library(janitor)
library(ISLR)
library(plotly)

# data
data <- OJ %>% 
    as_tibble() %>% 
    clean_names()

# plot
p <- data %>% 
    ggplot(aes(price_ch, purchase)) 
    geom_violin() 
    geom_jitter(aes(text = price_ch),width = 0.1, alpha = 0.5) 
    facet_wrap(~store7)
    
# plot with plotly
ggplotly(p, tooltip = "text")


CodePudding user response:

It seems you can not have your categorical feature on y axis in Plotly. enter image description here

CodePudding user response:

The link by M.Viking gave me the clue into this - but it's a bit more complicated than just adding coord_flip() because you have a geom_jitter(). You need to ensure that is flipped as well and change the width argument to height - otherwise you will end up jittering across the purchase axis, so there will still be overplotting.

p <- data |>
    ggplot()  
    geom_violin(
        aes(
            y = price_ch,
            x = purchase
        )
    )  
    coord_flip()  
    geom_jitter(
        aes(
            y = price_ch,
            x = purchase,
            text = price_ch
        ),
        height = 0.1,
        alpha = 0.5
    )  
    facet_wrap(~store7)

ggplotly(p)

enter image description here

  • Related