2014-10-10 19 views
0

X-axix標籤,我有這樣的功能:增加更多的ggplot

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軸,每個都有兩個過程的標籤。有沒有可能通過ggplot2來實現?

回答

3

您可以使用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

+0

酷!非常感謝。 – nan 2014-10-10 10:58:04