r - 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 轴显示相同的数字但没有胡萝卜。
解决方案
这可以通过函数来完成scale_x_log2
,scale_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)
编辑。
在评论中的讨论之后,这里有另外两种给出不同轴标签的方法。
- 轴标记每个刻度线。集合
limits = c(1.01, NA)
和函数参数n = 11
,奇数。 - 奇数指数上的轴标签。保留
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)
推荐阅读
- themes - 新主题中的样式 Filemaker 门户滚动条
- c# - Android 上的 MediaPlugin 无法播放声音
- git - Git,如何忽略切换行?
- android - 构建后的应用程序 --prod --release 仅在闪屏离子 3
- .net-core - .NET Core Identity Server 动态客户端应用注册和身份验证
- scala - 我应该如何优化 scala 代码并使其更具可读性
- r - 使用 R 基于其他列在时间序列中重复删除
- flutter - 类似 Spotify 的外观的 Sliver 导航颤动
- docker - 来自 Docker 的 Flutter Web 读取自定义环境
- reactjs - 如何在使用 redux-saga 的调度中等待完整的返回值?