分组的小提琴/箱形图中的中心x轴标签

时间:2018-07-10 10:20:28

标签: r ggplot2 axis-labels

我正在按组创建小提琴图。我想在每组小提琴图的中点居中使用希腊字母来标记每组。 我该怎么做?

到目前为止,我正在使用scale_x_discrete,但是我无法指定任何居中位置。

library(ggplot2)
dat <- matrix(rnorm(100*12),ncol=12)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- ifelse(mat$variable %in% c('X1', 'X2', 'X3','X4'), 'g1',
                                ifelse(mat$variable %in% c('X5','X6','X7','X8'), 
                                       'g2', 'g3'))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) + 
  geom_violin(scale="width",adjust = 1,width = 0.5) + 
  scale_x_discrete(labels = c(expression(theta[1]),"","","",expression(theta[2]),"","","",expression(theta[3])))
pp

enter image description here

在此示例中,标签应位于2.5、6.5和8.5。

2 个答案:

答案 0 :(得分:3)

另一种解决方案:

library(ggplot2)

pp <- ggplot(mat, aes(x = as.numeric(variable), y = value, 
                      group = variable, fill = variable_grouping)) + 
  geom_violin(scale="width", adjust = 1, width = 0.5) + xlab("variable") +
  scale_x_continuous(breaks = c(2.5, 6.5, 10.5), 
              labels = c(expression(theta[1]),expression(theta[2]),expression(theta[3])))
pp

enter image description here

答案 1 :(得分:2)

您可以手动更改theme中x轴标签的水平位置。

library(ggplot2)
ggplot(mat, aes(variable, value, fill = variable_grouping)) + 
    geom_violin(scale = "width", adjust = 1, width = 0.5) +
    scale_x_discrete(labels = c(expression(theta[1]), "", "", "",
                                expression(theta[2]), "", "", "",
                                expression(theta[3]))) +
    theme(axis.text.x = element_text(hjust = -8),
          axis.ticks.x = element_blank())

enter image description here

PS:我还删除了x轴刻度线。