添加在ggplot更多的X-axix标签(Adding more x-axix labels in

2019-10-21 03:10发布

我有这样的功能:

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)
}

此代码情节我图所示:

在这个情节我想绘制了两个疗程的类型和分数之间的关系,到目前为止,一切顺利。 但现在我想补充以下A,B和C分别第二x轴标贴,以显示每种类型的观测值的数量。 请注意,在代码中,我评论了scale_x_discrete 。 我知道这个功能让我可以每个级别下添加的东西。 但问题是,我有两个课程,DSP和RP。 所以,我想补充意见的数量都两门课程在X标识A,B,C,最好用绿色和黄色的颜色,以表示两个课程,这似乎并不可能与scale_x_discrete

我认为一个解决办法是增加当前的下两个额外的X轴,每两个课程的标签。 是否有可能与实现这一ggplot2

Answer 1:

您可利用geom_text来实现这一目标。 下面的代码是强烈影响这个问题 。 请注意,因为你的问题没有样本数据,我做我自己的可重复的例子 。

# 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)



文章来源: Adding more x-axix labels in ggplot
标签: r ggplot2