对齐水平ggplot条形图的标题,字幕和标题 [英] Aligning title, subtitle and caption for horizontal ggplot barchart
问题描述
我想在水平ggplot2条形图中左对齐plot.title
,plot.subtitle
和plot.caption
.
I would like to left align the plot.title
, plot.subtitle
and plot.caption
in a horizontal ggplot2 barchart.
示例:
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
的起始位置(红色垂直线,Manhatten的"M")?
How can I align all 3 labs
elements (plot.title
, plot.subtitle
and plot.caption
) to where the axis.text
starts (red vertical line, "M" of Manhatten)?
此外:为什么固定的myhjust
会导致plot.title
,plot.subtitle
和plot.caption
的3个不同的水平位置?
Besides: Why does a fixed myhjust
result in 3 different horizontal positions for plot.title
, plot.subtitle
and plot.caption
?
推荐答案
此问题涉及github tidyverse/ggplot2解决的问题: https://github.com/tidyverse/ggplot2/issues/3252
This question refers to this github tidyverse/ggplot2 solved issue: https://github.com/tidyverse/ggplot2/issues/3252
它在ggplot2(开发版本)中实现: https://github .com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md
And it is implemented in ggplot2 (development version): https://github.com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md
主题获得了两个新参数plot.title.position和plot.caption.position,可用于自定义情节标题/字幕和情节标题相对于整个情节的位置(@ clauswilke,#3252)
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
由 reprex软件包(v0.3.0)
Created on 2019-09-04 by the reprex package (v0.3.0)
这篇关于对齐水平ggplot条形图的标题,字幕和标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!