R plot()或ggplot2()中的对数y轴刻度标记

时间:2011-04-28 16:15:53

标签: r plot ggplot2 data-visualization

我在this paper中看到了log="y"图的理想刻度标记结构,图3b 3c 3d。

它有短的,对数间隔的小刻度标记,没有标签,加上带标签的长对数主刻度标记。

有谁知道如何在R中实现这一目标?

4 个答案:

答案 0 :(得分:11)

在基地R中,只需根据需要建立轴。这样的事情可能是一个开始。

set.seed(5)
d <- data.frame(x=1:100, y=rlnorm(100, meanlog=5, sdlog=3))
with(d, {
  plot(x, y, log="y", yaxt="n")
  y1 <- floor(log10(range(y)))
  pow <- seq(y1[1], y1[2]+1)
  ticksat <- as.vector(sapply(pow, function(p) (1:10)*10^p))
  axis(2, 10^pow)
  axis(2, ticksat, labels=NA, tcl=-0.25, lwd=0, lwd.ticks=1)
})

lattice中,latticeExtra包具有以下功能:

library(lattice)
library(latticeExtra)
xyplot(y~x, data=d, scales=list(y=list(log=10)),
       yscale.components=yscale.components.log10ticks)

答案 1 :(得分:6)

对于ggplot2,似乎您指定刻度的唯一选项是size(即宽度)。

# A plot of any old data
dfr <- data.frame(x = 1:100, y = rlnorm(100))
p <- ggplot(dfr, aes(x, y)) + 
  geom_point() +
  scale_y_log10(breaks = breaks, labels = breaks)


#Tick locations
get_breaks <- function(x)
{
  lo <- floor(log10(min(x, na.rm = TRUE)))
  hi <- ceiling(log10(max(x, na.rm = TRUE)))
  as.vector(10 ^ (lo:hi) %o% 1:9)
}

breaks <- get_breaks(dfr$y)
log10_breaks <- log10(breaks)

#Some bigger ticks
p + opts(axis.ticks = theme_segment(
    size = ifelse(log10_breaks == floor(log10_breaks), 2, 1)
  ))

答案 2 :(得分:3)

这是在package :: sfsmisc中完成的。请参阅help(axTexpr)

中的示例

答案 3 :(得分:1)

以下是ggplot2解决方案:

library(ggplot2)

set.seed(20180407)

df = data.frame(x = seq(from = 1, by = 1, length.out = 20),
                y = 2^(seq(to = 1, by = -1, length.out = 20) + rnorm(20, 0, 0.7)))

ggplot(data = df, aes(x = x, y = y)) +
  geom_line() +
  scale_y_log10() +
  annotation_logticks(sides = "l") 

example_plot

你可以使它看起来比你用一些主题链接的纸张更多:

ggplot(data = df, aes(x = x, y = y)) +
  geom_line(colour = "blue") +
  geom_point(colour = "blue") +
  scale_y_log10() +
  annotation_logticks(sides = "l") +
  theme_minimal() +
  theme(panel.grid = element_blank(), 
        axis.line = element_line(),
        axis.ticks.x = element_line())

example_themed