-1

The violin plot im currently trying to create shows tails going into the negative side of the y-axis. Is there anyway to remove the negative tail of these violin plots?

Im using this plotly function to generate the plot:

fig <- plot_ly(data = test_dt, source = 'violin_plot')

fig <- fig %>% add_trace( x = test_dt [[x_col()]], y = test_dt [[y_col()]],  width = .55,

                          showlegend = T,

                          box = list(visible = T),

                          spanmode = "soft",

                          meanline = list(visible = F),

                          color = test_dt[[x_col()]],

                          colors = "Set3",

                          type = "violin")

When I choose span = "hard", both sides (positive and negative) get cut-off. I want to keep the full positive span.

P.s. The number of plots is not fixed. It would be dynamic based on the x-axis variable.

Danish Zahid Malik
  • 541
  • 2
  • 7
  • 19

1 Answers1

0

I think there might be a conceptual misunderstanding here. Cutting off both positive and negative tails is desired behaviour.

One fundamental problem with density plots is that they may plot tails where there is no data (as you will have correctly recognised, thus your desire not to plot below zero). By creating a "hard" trim (geom_violin)/ spanmode (plotly) you are cutting off any data beyond the actual data range, and thus more truthfully representing your data.

Compare

library(plotly)

df <- data.frame(y = runif(n = 100, min = .1, max = 1))

range(df$y)
#> [1] 0.1107544 0.9984681

fig <- plot_ly(data = df, source = "violin_plot")

fig %>% add_trace(
  x = 1, y = df$y,
  box = list(visible = T),
  spanmode = "hard",
  type = "violin"
)

Created on 2023-05-17 with reprex v2.0.2

tjebo
  • 21,977
  • 7
  • 58
  • 94