我嘗試通過使用將標題移動到繪圖區域plot.title=element_text(hjust=0.02, vjust=-7)。但是,它將在繪圖的頂部區域顯示一個空白區域。
如何優雅地洗掉空白區域?
帶有標題的繪圖和繪圖頂部區域的空白區域在這里。
data <- data.frame(name=c('a','b','c','d'),
num=c(7, 2, 8, 12))
pp <- ggplot(data=data, aes(x=name, y=num, fill=name))
geom_bar(stat='identity')
labs(title='A Title Here')
theme(plot.title=element_text(hjust=0.02, vjust=-7))
ggsave(plot=pp, file='pp-a.png', height=6, width=5)
我們可以plot.margin用來洗掉空白:
pp <- ggplot(data=data, aes(x=name, y=num, fill=name))
geom_bar(stat='identity')
labs(title='A Title Here')
theme(plot.title=element_text(hjust=0.02, vjust=-7),
plot.margin=unit(c(-5,0.8,0.8,1.0),"mm"))
ggsave(plot=pp, file='pp-b.png', height=6, width=5)
但是,如果我們改變標題的字體大小,我們必須重新設定plot.margin。有沒有人有另一種優雅的方式?
謝謝你的幫助。
uj5u.com熱心網友回復:
而不是通過擺弄來移動繪圖示題hjust,vjust您可以使用 更優雅、更輕松地將標題添加到繪圖面板annotation_custom,例如在下面的代碼中,我將標題放在左上角并添加一些 5.5pt 的填充。而且由于您的情節現在沒有任何“標題”,因此這樣做會自動“洗掉”從我在情節周圍繪制的紅線可以看到的空白區域。
data <- data.frame(
name = c("a", "b", "c", "d"),
num = c(7, 2, 8, 12)
)
library(ggplot2)
ggplot(data = data, aes(x = name, y = num, fill = name))
geom_bar(stat = "identity")
annotation_custom(grob = grid::textGrob(
"A Title Here",
x = unit(0, "npc") unit(5.5, "pt"),
y = unit(1, "npc") - unit(5.5, "pt"),
hjust = 0, vjust = 1,
gp = grid::gpar(fontsize = 16)
))
theme(plot.background = element_rect(color = "red"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523457.html
標籤:rggplot2
