在ggplot中添加更多x轴标签

时间:2014-10-10 08:20:17

标签: r ggplot2

我有这样的功能:

plotMeansDouble <- function(data, labX)
{
  #xlabs <- paste(levels(stats::reorder(data$type, data$score,mean)),"\n(N=",levels(stats::reorder(data$N, data$score,mean)),"/",levels(stats::reorder(data$TN, data$score,mean)),")",sep="")
  ggplot(data, aes(x=microstyle, y=difficulty, ymax = Upper.CI, group= course, color=course)) + 
  geom_errorbar(aes(ymin=Lower.CI, ymax = Upper.CI ), width=.1, position=position_dodge(.2)) + 
  geom_line(, position=position_dodge(.2)) + 
  geom_text(aes(y=Upper.CI,label = pointlabel, vjust=-1),position=position_dodge(.2)) + 
  geom_point(size=3, shape=21, position=position_dodge(.2))+
  labs(x = labX, y = "Score") + 
  theme_bw()+ 
  theme(panel.grid.major = element_blank(), panel.border = element_blank(),axis.text=element_text(size=14), axis.title=element_text(size=18),axis.text.x=element_text(size=16, angle=40, vjust=.8, hjust=1.01)) #+ scale_x_discrete(labels=xlabs)
}

此代码绘制我的图形如下: enter image description here

在这个情节中,我想绘制两个课程的类型和分数之间的关系,到目前为止一直很好。但现在我想分别在A,B和C下面添加第二个x轴标记,以显示每种类型的观察数量。请注意,在代码中我评论了scale_x_discrete。我知道这个功能允许我在每个级别下添加一些东西。但问题是我有两门课程DSP和RP。因此,我想在x标签A,B,C下添加两个课程的观察次数,最好用绿色和黄色着色来代表两个课程,scale_x_discrete似乎无法实现。

我认为解决方案可以在当前的x轴下添加两个额外的x轴,每个x轴都有两个标记。是否可以使用ggplot2实现此目的?

1 个答案:

答案 0 :(得分:4)

您可以使用geom_text来实现此目的。以下代码受this question的强烈影响。请注意,由于您的问题中没有示例数据,因此我制作了自己的reproducible example

# load ggplot
require(ggplot2)
require(grid)
# creating sample data
set.seed(42)
df <- data.frame(Type = LETTERS[1:3], 
                 Score = runif(6), 
                 course = letters[1:2])
# data for text labels
text.a <- data.frame(Type = LETTERS[1:3], 
                      Score = -Inf,
                      course = 'a',
                      text = paste0('N=', 1:3))
text.b <- data.frame(Type = LETTERS[1:3], 
                     Score = -Inf,
                     course = 'b',
                     text = paste0('N=', 2:4))
# plotting commands
p <- ggplot(df, aes(Type, Score, color=course, group=course)) + 
  geom_point() +
  geom_line() +
  geom_text(data=text.a, aes(label = text), vjust=3, show_guide  = FALSE) +  # adding text for first course
  geom_text(data=text.b, aes(label = text), vjust=4.5, show_guide = FALSE) + # adding text for second course
  theme(plot.margin = unit(c(1,1,2,1), "lines")) + # making enough room 
  scale_x_discrete(name='\n\n\nType') # pushing down the legend

# turns clipping off
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

enter image description here

相关问题