我想知道如何在 R 中绘制 y 轴倒置的图,以便绘制的数据出现在笛卡尔平面的第四象限 ( IV ) 中,而不是第一 (I) 象限。
作为参考,我试图制作的情节看起来与以下(来源)非常相似:
我在网上找到了许多关于反转y 轴编号的问题,但这些问题仍然在第一象限中绘制数据。谁能建议我如何制作类似于上面显示的情节?
根据@timriffe 和@joran 的评论,只是为了提供一个可行的答案......
使用此答案中的次要日志滴答功能:
minor.ticks.axis <- function(ax,n,t.ratio=0.5,mn,mx,...){
lims <- par("usr")
if(ax %in%c(1,3)) lims <- lims[1:2] else lims[3:4]
major.ticks <- pretty(lims,n=5)
if(missing(mn)) mn <- min(major.ticks)
if(missing(mx)) mx <- max(major.ticks)
major.ticks <- major.ticks[major.ticks >= mn & major.ticks <= mx]
labels <- sapply(major.ticks,function(i)
as.expression(bquote(10^ .(i)))
)
axis(ax,at=major.ticks,labels=labels,...)
n <- n+2
minors <- log10(pretty(10^major.ticks[1:2],n))-major.ticks[1]
minors <- minors[-c(1,n)]
minor.ticks = c(outer(minors,major.ticks,`+`))
minor.ticks <- minor.ticks[minor.ticks > mn & minor.ticks < mx]
axis(ax,at=minor.ticks,tcl=par("tcl")*t.ratio,labels=FALSE)
}
制作一些可重现的示例数据:
x <- 1:8
y <- 10^(sort(runif(8, 1, 10), decreasing = TRUE))
没有轴的绘图:
plot(x, log10(y), # function to plot
xlab="", # suppress x labels
type = 'l', # specify line graph
xlim = c(min(x), (max(x)*1.3)), # extend axis limits to give space for text annotation
ylim = c(0, max(log10(y))), # ditto
axes = FALSE) # suppress both axes
添加花哨的日志轴并将刻度标签正确地向上转动(感谢@joran!):
minor.ticks.axis(2, 9, mn=0, mx=10, las=1)
在顶部添加 x 轴:
axis(3)
添加 x 轴标签(感谢提示,@WojciechSobala)
mtext("x", side = 3, line = 2)
并在行尾添加注释
text(max(x), min(log10(y)), "Example", pos = 1)
结果如下:
现在很容易使用scale_y_reverse
和指定position = "top"
x轴来反转 y 轴ggplot2
例子
library(ggplot2)
library(scales)
set.seed(99)
Date <- seq(from = as.Date("2017-12-01"), to = as.Date("2017-12-15"),
by = "days")
Flux <- runif(length(Date), 1, 10000)
Flux_df <- data.frame(Date, Flux)
p1 <- ggplot(Flux_df, aes(Date, Flux)) +
geom_col() +
xlab("") +
scale_x_date(position = "top", breaks = pretty_breaks(), expand = c(0, 0)) +
scale_y_reverse(expand = expand_scale(mult = c(0.2, 0))) +
theme_bw(base_size = 16) +
theme(panel.border = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line()) +
theme(legend.position = "none")
p1
如果我们想要对数轴和反向轴,我们需要这里建议的解决方法,因为ggplot2
atm 没有该选项
reverselog_trans <- function(base = exp(1)) {
trans <- function(x) -log(x, base)
inv <- function(x) base^(-x)
scales::trans_new(paste0("reverselog-", format(base)), trans, inv,
scales::log_breaks(base = base), domain = c(1e-100, Inf))
}
p1 + scale_y_continuous(trans = reverselog_trans(10),
breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x)),
expand = expand_scale(mult = c(0.2, 0))) +
annotation_logticks()