admin管理员组

文章数量:1125742

This is my initial code:

library(ggplot2)
library(dplyr)
library(plotly)
library(reshape2)

# Define the flex_boxplot function
draw_boxplot <- function(
    boxplot_data, 
    interactive = TRUE,
    user_colors = NULL, 
    user_title = "Boxplot",
    user_x_title = NULL,
    user_y_title = NULL,
    user_legend_title = NA,
    user_plot_theme = theme_minimal(),
    user_plot_theme_specs = theme(
      legend.title = element_blank(),
      legend.text = element_text(size = 10),
      title = element_text(size = 15),
      axis.text.x = element_text(size = 10),
      axis.title.x = element_text(size = 10),
      axis.text.y = element_text(size = 10),
      axis.title.y = element_text(size = 10)
    )
) {

  
  # Default color palette
  default_colors <- c("blue", "red", "green")
  
  # Use user-defined colors if provided, otherwise default
  colors <- if (!is.null(user_colors)) user_colors else default_colors[1:min(length(default_colors), ncol(boxplot_data))]
  
  # Melt data to long format, explicitly specifying no id variables
  data_long <- melt(boxplot_data, id.vars = NULL) # Set id.vars to NULL explicitly
  colnames(data_long) <- c("Variable", "Value")
  
  # Create the boxplot
  p <- ggplot(data_long, aes(x = Variable, y = Value, fill = Variable)) +
    geom_boxplot() +
    scale_fill_manual(values = colors) +
    labs(
      title = user_title,
      x = user_x_title,
      y = user_y_title,
      fill = user_legend_title
    ) +
    user_plot_theme +
    user_plot_theme_specs
  
  # Adjust legend display
  if (is.na(user_legend_title)) {
    p <- p + theme(legend.position = "none")
  }
  
  # Add interactivity if specified
  if (interactive) {
    return(ggplotly(p))
  } else {
    p
  }
}

# Example usage
set.seed(123)
example_data <- data.frame(
  Population_1 = rnorm(100, mean = 0, sd = 1),
  Population_2 = rgamma(100, shape = 2, rate = 1),
  Population_3 = runif(100, min = -2, max = 2)
)

# Basic boxplot
draw_boxplot(example_data)

I need to rename the following tooltip labels as given below: "upper fence:" to "upper whisker:" and "lower fence:" to lower whisker:" and remain the rest as they are.

I was trying with the option given here, but failed. ggplotly: rename tooltip on hover

本文标签: Renaming R plotly tooltip label in boxplotStack Overflow