ggplot stat_summary文本下标

k5hmc34c  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(262)

假设 Dataframe

df <- data.frame("Method" = rep(c("Method1", "Method2", "Method3", "Method4", "Method5"), each = 3, times = 1),
                 "Type" = rep(c("A", "B", "C"), 5),
                 "Value" = c(runif(5, 0, 1), runif(5, 0.2, 1.2), runif(5, 0.4, 1.4)))

我画了一个箱线图

get_box_stats <- function(y, upper_limit = max(df$Value) * 1.42) {
  return(data.frame(
    y = upper_limit,
    label = paste(
      "N =", length(y), "\n",
      "Q1 =", round(quantile(y, 0.25), 2), "\n",
      "M =", round(median(y), 2), "\n",
      "Q3 =", round(quantile(y, 0.75), 2), "\n"
    )
  ))
}

ggplot(df, aes(factor(Type), Value)) +
  labs(fill = "Method") +
  stat_summary(size = 4.6, fun.data = get_box_stats, geom = "text", position = position_dodge(.9),
               hjust = 0.5, vjust = 1, aes(group = factor(Type)))+
  geom_boxplot(coef = 0, aes(fill = factor(Type))) + theme_classic()+ 
  theme(legend.position = "top", axis.text.x = element_text(size = 15),
        axis.text.y = element_text(size = 15),  
        axis.title.x = element_text(size = 15),
        axis.title.y = element_text(size = 15),
        legend.title=element_text(size = 15), 
        legend.text=element_text(size = 15)) +
  geom_dotplot(aes(fill = factor(Type)), dotsize = 0.8, binaxis = 'y', stackdir = 'center',
               position = position_dodge(0.75))+
  xlab("Method")

看起来像

    • 问题:**如何将Q1更改为Q₁?我尝试过:
  • expression(Q[1])
  • bquote(Q[1])
  • 简单粘贴

但都不管用。

    • UPDATE:**使用Q\u2081 =不会显示下标,而是显示一个空的正方形。但是,在上面的代码中不使用时,它仍然有效。
rqmkfv5c

rqmkfv5c1#

使用Unicode subscripts可以执行以下操作:

library(ggplot2)

get_box_stats <- function(y, upper_limit = max(df$Value) * 1.42) {
  return(data.frame(
    y = upper_limit,
    label = paste(
      "N =", length(y), "\n",
      "Q\u2081 =", round(quantile(y, 0.25), 2), "\n",
      "M =", round(median(y), 2), "\n",
      "Q\u2083 =", round(quantile(y, 0.75), 2), "\n"
    )
  ))
}

ggplot(df, aes(factor(Type), Value)) +
  labs(fill = "Method") +
  stat_summary(size = 4.6, fun.data = get_box_stats, geom = "text", position = position_dodge(.9),
               hjust = 0.5, vjust = 1, aes(group = factor(Type)))+
  geom_boxplot(coef = 0, aes(fill = factor(Type))) + theme_classic()+ 
  theme(legend.position = "top", axis.text.x = element_text(size = 15),
        axis.text.y = element_text(size = 15),  
        axis.title.x = element_text(size = 15),
        axis.title.y = element_text(size = 15),
        legend.title=element_text(size = 15), 
        legend.text=element_text(size = 15)) +
  geom_dotplot(aes(fill = factor(Type)), dotsize = 0.8, binaxis = 'y', stackdir = 'center',
               position = position_dodge(0.75))+
  xlab("Method")
#> Bin width defaults to 1/30 of the range of the data. Pick better value with
#> `binwidth`.

相关问题