0

ENV

R version 3.3.1

MAC OSX 10.9.4

I would like to plot a style like figure below, which is plotted by matlab.

There is full grid on the plot with customized axis range (e.g. $10^0~10^{-4}$) and axis label (e.g. 10^0 10^1 10^-2 10^-3 10^-4 10^-5). There are ten ticks between 10^0 and 10^1 and also other labels. Similar for y axis.

Expected:

enter image description here

I tried:

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)

I got:

enter image description here

The axis and axis label and the ticks and grid is not what I want. Can anyone can give an advices? Thanks.

Community
  • 1
  • 1
Nick Dong
  • 3,638
  • 8
  • 47
  • 84

2 Answers2

2

Worst case scenario, you can just draw the axes and background lines yourself.

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

G5W
  • 36,531
  • 10
  • 47
  • 80
1

Here's an example - it's not exactly what you want (e.g. you could play around with theme options such as panel.grid.minor to get dotted grid lines), but it's most of the way there.

Exponential-format axis tick labels, from 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)
}

Manual ticks from @G5W's answer: might be possible to write a function to do this automatically, or one might exist somewhere.

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

Draw the plot (with @G5W's sample mini-data)

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

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453