2017-05-11 50 views
1

我正在尋找設置中間有一組軸標籤的鏡像條形圖。此圖片顯示了我到目前爲止(代碼在年底重現):ggplot:居中並移動垂直軸標籤

enter image description here

我想在圖表之間爲中心的名稱。方法嘗試:

  • 使用軸標籤(如圖所示最好的嘗試)
  • 使用annotation_custom(我發現放置標籤是非常困難和不喜歡ggplot引用和壘積引用的組合)
  • 創建單獨的「圖表對象」裝進grid.arrange面板(很難得到標籤之間正確的垂直間距,而不存在任何條)

我歡迎各地客商來實現這一佈局的最簡單方法的任何建議。基地必須是ggplot,但很樂意使用其他包來安排圖表。

require("ggplot2") 
require("gridExtra") 

dataToPlot <- data.frame(
    "Person" = c("Alice", "Bob", "Carlton"), 
    "Age" = c(14, 63, 24), 
    "Score" = c(73, 62.1, 21.5)) 

plot1 <- ggplot(dataToPlot) + 
    geom_bar(data = dataToPlot, aes(x = Person, y = Score), stat = "identity", 
    fill = "blue", width = 0.8) + 
    scale_y_continuous(trans = "reverse", expand = c(0, 0)) + 
    scale_x_discrete(position = "top") + 
    theme(
    axis.text.y = element_blank() 
) + 
    labs(x = NULL) + 
    coord_flip() 

plot2 <- ggplot(dataToPlot) + 
    geom_bar(data = dataToPlot, aes(x = Person, y = Age), stat = "identity", 
    fill = "red", width = 0.8) + 
    scale_y_continuous(expand = c(0, 0)) + 
    theme(
    axis.text.y = element_text(size = 20, hjust = 0.5) 
) + 
    labs(x = "") + 
    coord_flip() 

gridExtra::grid.arrange(plot1, plot2, ncol = 2, widths = c(1, 1.2)) 
+0

'element_text(大小= 20,hjust = 0.5)'應該居中 –

+0

謝謝你 - 去現貨。這將它們置於中心位置,但我也想將它們從軸線上移開一點。我會用正確的hjust值發佈更新後的圖片。 – Serenthia

+0

您可能需要調整該值,但'element_text(size = 20,hjust = 0.5,margin = margin(r = 30))'或多或少都適用於我。 –

回答

2

有兩種方法(可能在組合)...

添加保證金右側圖表中的軸標籤的權利......

element_text(size = 20, hjust = 0.5, margin=margin(r=30)) 

。 ..或者兩個圖表靠攏在一起

grid.arrange(plot1, plot2, ncol = 2, widths = c(1, 1.2),padding=0) 
+0

注意:在左邊的圖表中''labs(x = NULL)''也需要刪除那邊的所有填充 – Serenthia