我想左对齐 plot.title
, plot.subtitle
和 plot.caption
在水平 ggplot2 条形图中。
例子:
library("ggplot2") # ggplot2 2.2
df <- data.frame(type=factor(c("Brooklyn",
"Manhatten and\n Queens")),
value=c(15,30))
# manual hjust for title, subtitle & caption
myhjust <- -0.2
ggplot(df,
aes(x=type, y=value)) +
geom_bar(stat='identity') +
coord_flip() +
labs(
title = "This is a nice title",
subtitle = "A subtitle",
caption = "We even have a caption. A very long one indeed.") +
theme(axis.title=element_blank(),
plot.title=element_text(hjust = myhjust),
plot.subtitle=element_text(hjust = myhjust ),
plot.caption=element_text(hjust = myhjust))
如何对齐所有 3 个
labs
元素( plot.title
、 plot.subtitle
和 plot.caption
)到 axis.text
的位置开始(红色竖线,曼哈顿的“M”)?此外:为什么固定
myhjust
为 plot.title
产生 3 个不同的水平位置, plot.subtitle
和 plot.caption
?最佳答案
这个问题是指这个 github tidyverse/ggplot2 解决的问题:https://github.com/tidyverse/ggplot2/issues/3252
并在ggplot2(开发版)中实现:https://github.com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md
Themes have gained two new parameters, plot.title.position and plot.caption.position, that can be used to customize how plot title/subtitle and plot caption are positioned relative to the overall plot (@clauswilke, #3252).
以您的示例为代表:
# First install the development version from GitHub:
#install.packages("devtools") #If required
#devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
packageVersion("ggplot2")
#> [1] '3.2.1.9000'
df <- data.frame(type=factor(c("Brooklyn","Manhatten and\n Queens")),
value=c(15,30))
ggplot(df, aes(x=type, y=value)) +
geom_bar(stat='identity') +
coord_flip() +
labs(title = "This is a nice title",
subtitle = "A subtitle",
caption = "We even have a caption. A very long one indeed.") +
theme(plot.caption = element_text(hjust = 0, face= "italic"), #Default is hjust=1
plot.title.position = "plot", #NEW parameter. Apply for subtitle too.
plot.caption.position = "plot") #NEW parameter
创建于 2019-09-04 由 reprex package (v0.3.0)
关于r - 对齐水平 ggplot 条形图的标题、副标题和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105759/