r - 对齐水平 ggplot 条形图的标题、副标题和标题

标签 r plot ggplot2

我想左对齐 plot.title , plot.subtitleplot.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.titleplot.subtitleplot.caption )到 axis.text 的位置开始(红色竖线,曼哈顿的“M”)?

此外:为什么固定myhjustplot.title 产生 3 个不同的水平位置, plot.subtitleplot.caption ?

Problem

最佳答案

这个问题是指这个 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/

相关文章:

r - 在ggplot 2中,如何连接geom_line中的起点和终点

matlab - 同时将 matlab 图形中的多条线条颜色设置为不同的值

R ggplot2 两级构面包裹

r - ggplot2:用geom_bar绘制平均值

c++ - Armadillo vector 类的 RcppArmadillo 样本

arrays - 由于n-1维数组且没有循环,如何从n维数组中提取n-1维数组?

r - 在 R 中,从列表中提取对象的一部分

python - 为什么水平线在 sage/matplotlib 中仅部分显示?

Matlab 轴在非交互模式下调整大小行为异常

r - 如何在ggplot2绘图区域上获得一种以上的背景颜色?