2016-09-18 198 views
0

我一直在試圖將我的圖例標題轉移到使用引導函數集中在圖例內容上。我一直在嘗試使用下面的代碼:在ggplot2中移動圖例標題

guides(colour=guide_legend(title.hjust = 20)) 

我想過試圖使可再現的例子,但我認爲它不工作的原因有事情做與上面的線不匹配的其餘部分我代碼具體。因此,這裏是我用我的陰謀代碼的其餘部分:

NH4.cum <- ggplot(data=NH4_by_Date, aes(x=date, y=avg.NH4, group = CO2, colour=CO2)) + 
    geom_line(aes(linetype=CO2), size=1) +    #line options 
    geom_point(size=3) +          #point symbol sizes 
    #scale_shape_manual(values = c(1, 16)) +     #manually choose symbols 
    theme_bw()+ 
    theme(axis.text.x=element_text(colour="white"), #change x axis labels to white. 
     axis.title=element_text(size=12), 
    axis.title.x = element_text(color="white"), #Change x axis label colour to white 
    panel.border = element_blank(),       #remove box boarder 
     axis.line.x = element_line(color="black", size = 0.5),  #add x axis line 
     axis.line.y = element_line(color="black", size = 0.5),  #add y axis line 
     legend.key = element_blank(),           #remove grey box from around legend 
     legend.position = c(0.9, 0.6))+            #change legend position 
    geom_vline(xintercept=c(1.4,7.5), linetype="dotted", color="black")+ #put in dotted lines for season boundaries 
    scale_color_manual(values = c("#FF6600", "green4", "#0099FF"), 
       name=expression(CO[2]~concentration~(ppm))) +     #manually define line colour 
    scale_linetype_manual(guide="none", values=c("solid", "solid", "solid")) +  #manually define line types 
    scale_shape_manual(values = c(16, 16, 16)) +     #manually choose symbols 
    guides(colour=guide_legend(title.hjust = 20))+ 
    scale_y_continuous(expand = c(0, 0), limits = c(0,2200), breaks=seq(0,2200,200))+  #change x axis to intercept y axis at 0 
    xlab("Date")+ 
    ylab(expression(Membrane~available~NH[4]^{" +"}~-N~(~mu~g~resin^{-1}~14~day^{-1})))+ 
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ 
    geom_errorbar(aes(ymin = avg.NH4 - se.NH4,    #set y error bars 
       ymax = avg.NH4 + se.NH4), 
      width=0.1) 

我曾嘗試做而不是下面沒有運氣:

guides(fill=guide_legend(title.hjust=20) 

我也紛紛調整了從值hjust值之間-2至20只是爲了看看是否有所作爲,但事實並非如此。

我會嘗試添加一張圖的圖片,所以你可以看到我在說什麼。 Note: I'm trying to shift the Co2 concentration (ppm) title to be centered over the legend objects

我已經查看了所有關於堆棧溢出的問題,並且據我所知,這不是重複的,因爲它是特定於我自己某處的編碼錯誤。 提前感謝您!

回答

1

明顯的方法例如

theme(legend.title = element_text(hjust = .5)) 

對我不起作用。我想知道它是否與的ggplot2有關。在任何情況下,一個手動的方法將是除去圖例標題和位置手動一個新的:

ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) + 
    geom_point() + 
    stat_smooth(se = FALSE) + 
    theme_bw() + 
    theme(legend.position = c(.85, .6), 
     legend.title = element_blank(), 
     legend.background = element_rect(fill = alpha("white", 0)), 
     panel.grid.major = element_blank(), 
     panel.grid.minor = element_blank()) + 
    annotate("text", x = 5, y = 27, size = 3, 
      label = "CO[2]~concentration~(ppm)", parse = TRUE) 

輸出: enter image description here