gpt4 book ai didi

r - 通过表达式生成时如何在ggplot2中对齐标题和副标题

转载 作者:行者123 更新时间:2023-12-04 23:42:13 24 4
gpt4 key购买 nike

我正在使用下面的代码在 ggplot2 中生成一个简单的箱线图:

# Libs data
data("mtcars"); require(ggplot2); require(ggthemes)
# Chart
ggplot(data = mtcars) +
geom_boxplot(aes(y = wt, x = as.factor(am)),
fill = "gray87") +
xlab("AM") +
ylab("WT") +
theme_gdocs() +
ggtitle("WT by AM") +
theme(axis.title.y = element_text(angle = 90),
axis.ticks = element_line(colour = "black", linetype = "solid",
size = 0.5),
panel.grid = element_line(colour = "gray"))
生成的图表相当简单:
First chart
任务
我想为我的图表添加一个副标题,并对它的呈现方式进行一些控制。我正在关注 this discussion并使用代码:
# Chart
ggplot(data = mtcars) +
geom_boxplot(aes(y = wt, x = as.factor(am)),
fill = "gray87") +
xlab("AM") +
ylab("WT") +
theme_gdocs() +
ggtitle(expression(atop("WT by AM",
atop(italic("Some crucial note that has to be here"), "")))) +
theme(axis.title.y = element_text(angle = 90),
axis.ticks = element_line(colour = "black", linetype = "solid",
size = 0.5),
panel.grid = element_line(colour = "gray"))
我得到以下图表:
second attempt

这看起来很糟糕,我想改变一些事情:
  • 使副标题和标题都左对齐
  • 减少两行之间的空白
  • 保留 字体加粗

  • 尝试
    我尝试了不同的东西,例如下面的代码:
    ggplot(data = mtcars) +
    geom_boxplot(aes(y = wt, x = as.factor(am)),
    fill = "gray87") +
    xlab("AM") +
    ylab("WT") +
    theme_gdocs() +
    ggtitle(expression(atop("WT by AM",
    atop(italic("Stupid note"), "")))) +
    theme(axis.title.y = element_text(angle = 90),
    axis.ticks = element_line(colour = "black", linetype = "solid",
    size = 0.5),
    panel.grid = element_line(colour = "gray"),
    plot.title = element_text(size = 16, colour = "black", hjust = -1))
    但它完全隐藏了标题:
    missing title

    最佳答案

    目前 Github 上有一个新版本的 ggplot2 (2.1.0.9000+) 可以解决您的问题。如需更多信息,请参阅 Bob Rudis' vignette.

    devtools::install_github("hadley/ggplot2")  # Until the new version is available on CRAN
    library(ggplot2)
    library(ggthemes) # Only necessary because the OP used theme_gdocs()

    ggplot(data = mtcars) +
    geom_boxplot(aes(y = wt, x = as.factor(am)), fill = "gray87") +
    xlab("AM") +
    ylab("WT") +
    theme_gdocs() +
    ggtitle("WT by AM", subtitle = "pearl of wisdom") + # subtitle is a new argument. Both are now left-justified by default
    theme(plot.title=element_text(margin=margin(b=0), size = 20), plot.subtitle=element_text(margin=margin(t=5, b = 10))) # Changing the size and margins of the title and subtitles to give the OP some options.

    Title and Subtitle Image

    关于r - 通过表达式生成时如何在ggplot2中对齐标题和副标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088432/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com