首页 > 解决方案 > ggplot2 轴文本中的上标

问题描述

我想创建一个在轴上有上标的图表,而不是使用ggplot2. 我知道有很多答案会更改轴标签,但不会更改轴文本。我不是要更改图表的标签,而是要更改轴上的文本。

例子:

x<-c('2^-5','2^-3','2^-1','2^1','2^2','2^3','2^5','2^7','2^9','2^11','2^13')
y<-c('2^-5','2^-3','2^-1','2^1','2^2','2^3','2^5','2^7','2^9','2^11','2^13')
df<-data.frame(x,y)
p<-ggplot()+
  geom_point(data=df,aes(x=x,y=y),size=4)
p

所以我希望 x 轴显示相同的数字但没有胡萝卜。

在此处输入图像描述

标签: rggplot2

解决方案


这可以通过函数来​​完成scale_x_log2scale_y_log2可以在 GitHub 包中找到jrnoldmisc

首先,安装软件包。

devtools::install_github("jrnold/rubbish")

然后,将变量强制为数字。我将使用原始数据框的副本。

df1 <- df
df1[] <- lapply(df1, function(x){
  x <- as.character(x)
  sapply(x, function(.x)eval(parse(text = .x)))
})

现在,绘制它。

library(jrnoldmisc)
library(ggplot2)
library(MASS)
library(scales)

a <- ggplot(df1, aes(x = x, y = y, size = 4)) + 
  geom_point(show.legend = FALSE) +
  scale_x_log2(limits = c(0.01, NA), 
                labels = trans_format("log2", math_format(2^.x)),
                breaks = trans_breaks("log2", function(x) 2^x, n = 10)) +
  scale_y_log2(limits = c(0.01, NA),
                labels = trans_format("log2", math_format(2^.x)),
                breaks = trans_breaks("log2", function(x) 2^x, n = 10))
a + annotation_logticks(base = 2)

在此处输入图像描述

编辑。

在评论中的讨论之后,这里有另外两种给出不同轴标签的方法。

  1. 轴标记每个刻度线。集合limits = c(1.01, NA)和函数参数n = 11,奇数。
  2. 奇数指数上的轴标签。保留limits = c(0.01, NA),更改为function(x) 2^(x - 1), n = 11

只是说明,没有情节。

首先。

a <- ggplot(df1, aes(x = x, y = y, size = 4)) + 
  geom_point(show.legend = FALSE) +
  scale_x_log2(limits = c(1.01, NA), 
                labels = trans_format("log2", math_format(2^.x)),
                breaks = trans_breaks("log2", function(x) 2^(x), n = 11)) +
  scale_y_log2(limits = c(1.01, NA),
                labels = trans_format("log2", math_format(2^.x)),
                breaks = trans_breaks("log2", function(x) 2^(x), n = 11))
a + annotation_logticks(base = 2)

第二个。

a <- ggplot(df1, aes(x = x, y = y, size = 4)) + 
  geom_point(show.legend = FALSE) +
  scale_x_log2(limits = c(0.01, NA), 
               labels = trans_format("log2", math_format(2^.x)),
               breaks = trans_breaks("log2", function(x) 2^(x - 1), n = 11)) +
  scale_y_log2(limits = c(0.01, NA),
               labels = trans_format("log2", math_format(2^.x)),
               breaks = trans_breaks("log2", function(x) 2^(x - 1), n = 11))
a + annotation_logticks(base = 2)

推荐阅读