R语言 包含上标的图例标题换行

e4eetjau  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(214)

如何 Package 带有上标的ggplot()图例标题?在下面的例子中,我想在“温度”一词之后 Package 图例标题
示例数据(尝试\n

library(tidyverse)
library(ggtext)
library(ggplot2)

ggplot(mtcars, aes(x = disp, y = hp, fill = hp, size = mpg)) +
  geom_point(shape = 21) +
  scale_fill_gradient2(low = "blue", high = "red",
                       midpoint = mean(mtcars$hp),
                       name = 'Air Temperature \nTrend (<sup>o</sup>C yr<sup>-1</sup>)') +
  scale_size_continuous(name = 'Air Temperature \nTrend (<sup>o</sup>C yr<sup>-1</sup>)') +
  theme(legend.title = element_markdown())

在这个例子中,有一个类似的SO问题(link here)对我不起作用。

nameFill <- bquote(atop(Air~Temperature~phantom(),
                         Trend~(degree*C~yr^-1)))

ggplot(mtcars, aes(x = disp, y = hp, fill = hp, size = mpg)) +
  geom_point(shape = 21) +
  scale_fill_gradient2(low = "blue", high = "red",
                       midpoint = mean(mtcars$hp),
                       name = nameFill) +
  scale_size_continuous(name = nameFill) +
  theme(legend.title = element_markdown())

wz3gfoph

wz3gfoph1#

使用ggtext时,必须使用<br>标记而不是\n来添加换行符:

library(ggtext)
library(ggplot2)

ggplot(mtcars, aes(x = disp, y = hp, fill = hp, size = mpg)) +
  geom_point(shape = 21) +
  scale_fill_gradient2(
    low = "blue", high = "red",
    midpoint = mean(mtcars$hp),
    name = "Air Temperature<br>Trend (<sup>o</sup>C yr<sup>-1</sup>)"
  ) +
  scale_size_continuous(name = "Air Temperature<br>Trend (<sup>o</sup>C yr<sup>-1</sup>)") +
  theme(legend.title = element_markdown())

当使用atop方法时,必须删除element_markdown

nameFill <- bquote(
  atop(
    Air ~ Temperature,
    Trend ~ (degree * C ~ yr^-1)
  )
)

ggplot(mtcars, aes(x = disp, y = hp, fill = hp, size = mpg)) +
  geom_point(shape = 21) +
  scale_fill_gradient2(
    low = "blue", high = "red",
    midpoint = mean(mtcars$hp),
    name = nameFill
  ) +
  scale_size_continuous(name = nameFill)

相关问题