如何在 ggplot2 的轴标签中使用上标

问题描述 投票:0回答:5

如何在x轴上打印埃平方?我尝试如下。

labs(x = "x axis" (Å^2)", y = "y axis")
r ggplot2
5个回答
44
投票

我们可以使用

bquote

library(ggplot2)
ggplot(mtcars, aes(hp, mpg)) + 
       geom_point() +
       labs(x = bquote('x axis'~(Å^2)), y = "y axis") +
       #or
       #labs(x = bquote('x axis'~(ring(A)^2)), y = "y axis") 
       theme_bw()


33
投票

你应该使用表达式,最好结合粘贴,如下:

ggplot(mtcars, aes(hp, mpg)) + geom_point() + labs(x = expression(paste("x axis ", ring(A)^2)), y = "y axis")


4
投票

您可以简单地使用:

ggplot(mtcars, aes(hp, mpg)) +  geom_point() +  labs(x = x~axis~ring(A)^2, y = "y axis")

4
投票

另一个选择是使用 ggtext 包。它允许使用 markdown 标签,我发现这样更容易编写和阅读。

library(ggtext)
library(ggplot2)
ggplot(mtcars, aes(hp, mpg)) +
  labs(x = "x axis (Å^(2))", y = "y axis") +
  ## use markdown theme for simple superscripts
  theme(axis.title.x = element_markdown())

reprex 包于 2022 年 7 月 14 日创建(v2.0.1)


0
投票

使用 < sup> 2 < /sup> (无空格)代替 ^ ,它应该可以工作! https://cran.r-project.org/web/packages/ggtext/vignettes/theme_elements.html

© www.soinside.com 2019 - 2024. All rights reserved.