我不太確定你以後的樣子,但是這顯示了兩種方法在文字面板外定位文字。對於這兩種方法,第一項任務是創建一個新的文本grob,其中包含文本「更輕」和「更深」。第一種方法使用gtable
函數定位新grob,gtable_add_grob
;第二種方法使用ggplot
函數定位grob,annotation_custom
。
# Your data
data = read.table(text = ' "Subject" "Cond" "Distortion"
"1" "White" 10.7
"2" "White" 19.4
"3" "White" 15.9
"4" "White" 13.5
"5" "White" 15.4
"1" "Ambiguous" 13.4
"2" "Ambiguous" 11.4
"3" "Ambiguous" 8.9
"4" "Ambiguous" 11.0
"5" "Ambiguous" 11.4
"1" "Black" 8.4
"2" "Black" 1.7
"3" "Black" 7.7
"4" "Black" 8.0
"5" "Black" 5.7', header = TRUE)
library(ggplot2)
library(gtable)
library(grid)
# The plot
p <- ggplot(data, aes(x = Cond, y = Distortion)) +
stat_summary(fun.y = mean, geom = "bar", position = "dodge",
fill = "Gray", colour = "black") +
stat_summary(fun.data = mean_cl_normal, geom = "errorbar",
position = position_dodge(width = 0.90), width = 0.2) +
labs(x = "Faces", y = "Lightness Distortion (gray levels)") +
theme_bw()
## Using `gtable` to position the text grob
# Set up text grob
text.grob1 <- textGrob("Darker", y = 0, just = "left",
rot = 90, gp = gpar(fontsize = 10, col = "red", fontface = "italic"))
text.grob2 <- textGrob("Lighter", y = 1, just = "right",
rot = 90, gp = gpar(fontsize = 10, col = "red", fontface = "italic"))
# Combine them into a single grob
text.grob <- gTree(children = gList(text.grob1, text.grob2))
# Get ggplot grob
g <- ggplotGrob(p)
# Add the grob to the column containing the y axis title
pos = subset(g$layout, grepl("ylab-l", name), t:l)
g <- gtable_add_grob(g, text.grob, l = pos$l, t = pos$t)
# Draw it
grid.newpage()
grid.draw(g)
## Using `annotation_custom` to position the text grob
# Set up text grob
text.grob1 <- textGrob("Lighter", y = 0, just = "left",
rot = 90, gp = gpar(fontsize = 10, col = "red", fontface = "italic"),
vjust = -2.5)
text.grob2 <- textGrob("Darker", y = 1, just = "right",
rot = 90, gp = gpar(fontsize = 10, col = "red", fontface = "italic"),
vjust = -2.5)
# Combine them into a single grob
text.grob <- gTree(children = gList(text.grob1, text.grob2))
# Add the grob to the plot
p <- p + annotation_custom(text.grob,
xmin = -Inf, xmax = -Inf, ymin = Inf, ymax = -Inf)
# The new grob is positioned outside the plot panel.
# To see the grob, clipping needs to be turned off.
g = ggplotGrob(p)
g$layout$clip <- "off"
# Draw it
grid.newpage()
grid.draw(g)
謝謝桑迪!我結束了使用方法#1(gtable),而是使用了字符串「Darker - Lighter」的單個文本grob。我對textGrob的y位置參數進行了大量的「試驗和錯誤」調整,並最終得到了與y軸上的零點很好對齊的短劃線。感謝所有有用的信息!乾杯 – Moonbootica