如何使用R plot绘制matlab样式的log-log图

时间:2017-01-28 15:14:17

标签: r matlab plot

ENV

R版本3.3.1

MAC OSX 10.9.4

我想绘制如下图所示的样式,由matlab绘制。

图上有完整的网格,有自定义的轴范围(例如$ 10 ^ 0~10 ^ { - 4} $)和轴标签(例如10 ^ 0 10 ^ 1 10 ^ -2 10 ^ -3 10 ^ - 4 10 ^ -5)。在10 ^ 0和10 ^ 1之间有十个刻度以及其他标签。 y轴相似。

预期:

enter image description here

我试过了:

initial.dir<-getwd()
setwd("/Rworks/bin")
sink("r.o")
pk <- read.table("2017.file)
rownames(pk)<-c("k","pk")
d.f <- data.frame(t(pk))
png(file="m.png")
plot(
  d.f$k,
  d.f$pk,
  type = "n",
  log = "xy",
  xlim = c( 10^0, 10^2),
  ylim = c( 0.00001, 1),
)
lines( d.f$k, d.f$pk, col = "green4", lty = "dotted")
points( d.f$k, d.f$pk, bg = "limegreen", pch = 21 )
box()
dev.off
sink()
setwd(initial.dir)

我得到了:

enter image description here

轴和轴标签以及刻度和网格不是我想要的。任何人都可以提出建议吗?感谢。

2 个答案:

答案 0 :(得分:2)

最糟糕的情况是,您可以自己绘制轴和背景线。

plot(
   x=c(1,2), y=c(0.6,0.2),
   pch=21,  bg="red",
   log = "xy",
   xlim = c( 10^0, 10^2),
   ylim = c( 0.00001, 1),
   xaxt="n", yaxt="n",
   xlab="",  ylab="",   
   yaxs="i"
)
lines(x=c(1,2), y=c(0.6,0.2))

axis(1, at=10^(0:2), 
    labels=expression(10^0, 10^1, 10^2))
axis(2, at=10^(-5:0),  las=1,
    labels=expression(10^-5, 10^-4, 10^-3, 10^-2, 10^-1, 10^0))

abline(h=outer((1:10),(10^(-5:-1))), col="#00000033", lty=2)
abline(v=outer((1:10),(10^(0:1))), col="#00000033", lty=2)

Log Plot

答案 1 :(得分:1)

以下是一个示例 - 它并不完全符合您的要求(例如,您可以使用panel.grid.minor这样的主题选项来获取虚线网格线),但它大部分都在那里。

来自here的指数格式轴刻度标签:

 fancy_scientific <- function(l) {
     # turn in to character string in scientific notation
     l <- format(l, scientific = TRUE)
     # quote the part before the exponent to keep all the digits
     l <- gsub("^(.*)e", "'\\1'e", l)
     # turn the 'e+' into plotmath format
     l <- gsub("e", "%*%10^", l)
     # return this as an expression
     parse(text=l)
}

来自@ G5W答案的手动勾选:可以自动编写一个函数来执行此操作,或者可能存在某个函数。

yticks = outer((1:10),(10^(-5:-1)))
xticks = outer((1:10),(10^(0:1)))

绘制图(使用@ G5W的样本迷你数据)

library(ggplot2)
ggplot(data.frame(x=1:2,y=c(0.6,0.2)),
        aes(x,y))+
geom_point(colour="red")+
scale_x_log10(limits=c(1,100),labels=fancy_scientific,
              minor_breaks=xticks)+
scale_y_log10(limits=c(1e-5,1),labels=fancy_scientific,
              minor_breaks=yticks)+
theme_bw()

enter image description here

相关问题