Skip to content

R plotly boxplots overwriting with numerical labels #2274

Open
@geejaytee

Description

@geejaytee

R plotly boxplots overwriting with numerical labels

I've asked this question on SO here: https://stackoverflow.com/questions/76466189/r-plotly-boxplots-overwriting-with-numerical-labels, but I'm wondering if it's a bug with the latest versions of the plotly library in R

Plotting boxplots with numeric (or numeric-as-character) as x-variable results in boxplots a) not located in the correct locations and b) with boxes overplotted

library(plotly)

colors <- c("red","blue","green","pink","brown")
data.in <- data.frame(Age=25*rnorm(100)+50, IMD=sample(5,100,replace=TRUE))
fig <- plot_ly(data=data.in[data.in$IMD == "1",], y=~Age, type="box", color=I(colors[1]),name="1 - least")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "2",], y=~Age, type="box", color=I(colors[2]),name="2")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "3",], y=~Age, type="box", color=I(colors[3]),name="3")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "4",], y=~Age, type="box", color=I(colors[4]),name="4")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "5",], y=~Age, type="box", color=I(colors[5]),name="5 - most")
fig <- fig %>% layout(yaxis = list(title = "Age"),
                      xaxis = list(title = "IMD"),
                      boxgap = 0.1, boxgroupgap=0)

This results in a plot similar to
Screenshot 2023-06-13 at 15 41 15
Specifying 'x=~' in each add_trace does place the boxes in the correct places so is a temporary workaround, but I think that this may be a bug with the package, as the above code with labels which don't start with numbers (in the 'name=' attribute) does give the correct placement:

library(plotly)

colors <- c("red","blue","green","pink","brown")
data.in <- data.frame(Age=25*rnorm(100)+50, IMD=sample(5,100,replace=TRUE))
fig <- plot_ly(data=data.in[data.in$IMD == "1",], y=~Age, type="box", color=I(colors[1]),name="A")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "2",], y=~Age, type="box", color=I(colors[2]),name="B")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "3",], y=~Age, type="box", color=I(colors[3]),name="C")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "4",], y=~Age, type="box", color=I(colors[4]),name="D")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "5",], y=~Age, type="box", color=I(colors[5]),name="E")
fig <- fig %>% layout(yaxis = list(title = "Age"),
                      xaxis = list(title = "IMD"),
                      boxgap = 0.1, boxgroupgap=0)
Screenshot 2023-06-13 at 17 39 13

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions