Specifying xlim and ylim when using log-scale in R
On a log-scale, 0 is minus infinity. Change your lower limit to 0.000001 or something and you'll be fine, eg this works:
plot(1:10, xlim=c(0.001,10), ylim=c(0.001,10), log="xy")
Setting ylim in R with a log scale AND setting tick values
set.seed(42)
mydata = data.frame(y = c(sample(10:100000,200)))
boxplot(mydata$y, log = "y", yaxt = "n", ylim = c(10,100000), xaxs="i", yaxs="i")
axis(side=2, font=1, at = c(10,100,1000,10000,100000),
labels = c("10", "100", "1,000","10,000","100,000"), las =2)
How can I set axis ranges in ggplot2 when using a log scale?
Much of ggplot2 is simply clearer to me if one doesn't use qplot
. That way you aren't cramming everything into a single function call:
df <- data.frame(x = 1:10,
y = seq(1e6,1e8,length.out = 10))
ggplot(data = df,aes(x = x, y =y)) +
geom_point() +
scale_y_log10(limits = c(1,1e8))
I'm going to assume you didn't really mean a y axis minimum of 0, since on a log scale that, um, is problematic.
R ggplot cannot set log axis limits
I think your problem is that log(0) is undefined (or -Inf for R), so you can't set the x limit to 0 on a log transformed axis without getting an error.
My usual workaround is to set the axis limit to 1 (because log(1) = 0), as below.
ggplot(s1_to_5_adj, aes(x = PfMSP119_adj))+
geom_histogram(bins = 1500) +
ylim(c(0,150)) +
scale_x_log10(limit = c(1,25000)) +
xlab("MFI value") +
ylab("Frequency") +
labs(title = "Age 1-5") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(panel.grid.minor=element_blank(),
panel.grid.major=element_blank())
Logarithmic scale plot in R
You can generate the values of p
using code like the following:
p <- 10^(seq(-4,0,0.2))
You want your x values to be evenly spaced on a log10 scale. This means you need to take evenly spaced values as the exponent for the base 10, because the log10 scale takes the log10 of your x values, which is the exact opposite operation.
With this, you are already pretty far. You don't need par(new=TRUE)
, you can simply use the function plot
followed by the function points
. The latter does not redraw the whole plot. Use the argument log = 'x'
to tell R you need a logarithmic x axis. This only needs to be set in the plot
function, the points
function and all other low-level plot functions (those who do not replace but add to the plot) respect this setting:
plot(p,trans, ylim = c(0,1), ylab='coeff', log='x')
points(p,path, ylim = c(0,1), ylab='coeff',pch=15)
EDIT: If you want to replicate the log-axis look of the above plot, you have to calculate them yourselves. Search the internet for 'R log10 minor ticks' or similar. Below is a simple function which can calcluate the appropriate position for log axis major and minor ticks
log10Tck <- function(side, type){
lim <- switch(side,
x = par('usr')[1:2],
y = par('usr')[3:4],
stop("side argument must be 'x' or 'y'"))
at <- floor(lim[1]) : ceil(lim[2])
return(switch(type,
minor = outer(1:9, 10^(min(at):max(at))),
major = 10^at,
stop("type argument must be 'major' or 'minor'")
))
}
After you have defined this function, by using the above code, you can call the function inside the axis(...)
function, which draws axes. As a suggestion: save the function away in its own R script and import that script at the top of your calculation using the function source
. By this means, you can reuse the function in future projects. Prior to drawing the axes, you have to prevent plot
from drawing default axes, so add the parameter axes = FALSE
to your plot
call:
plot(p,trans, ylim = c(0,1), ylab='coeff', log='x', axes=F)
Then you may generate the axes, using the tick positions generated by the
new function:
axis(1, at=log10Tck('x','major'), tcl= 0.2) # bottom
axis(3, at=log10Tck('x','major'), tcl= 0.2, labels=NA) # top
axis(1, at=log10Tck('x','minor'), tcl= 0.1, labels=NA) # bottom
axis(3, at=log10Tck('x','minor'), tcl= 0.1, labels=NA) # top
axis(2) # normal y axis
axis(4) # normal y axis on right side of plot
box()
As a third option, as you are importing ggplot2 in your original post: The same, without all of the above, with ggplot:
# Your data needs to be in the so-called 'long format' or 'tidy format'
# that ggplot can make sense of it. Google 'Wickham tidy data' or similar
# You may also use the function 'gather' of the package 'tidyr' for this
# task, which I find more simple to use.
d2 <- reshape2::melt(x, id.vars = c('v1'), measure.vars = c('v2','v3'))
ggplot(d2) +
aes(x = v1, y = value, color = variable) +
geom_point() +
scale_x_log10()
R how to automatically adjust y axis when using basic plot with xlim
Subset the relevant data and plot that
lower = 40
upper = 60
ind = which(x >= lower & x <= upper)
plot(x[ind], y[ind], type = "l")
ggplot2: log10-scale and axis limits
ggplot(data = df,aes(x = x, y =y)) +
geom_point() +
scale_y_log10(limits = c(1,1e8), expand = c(0, 0))
Related Topics
R Formatting a Date from a Character Mmm Dd, Yyyy to Class Date
Hashtag Extract Function in R Programming
Confidence Intervals for Predictions from Logistic Regression
Screening (Multi)Collinearity in a Regression Model
What Are Some Good Books, Web Resources, and Projects for Learning R
Delete Rows with Blank Values in One Particular Column
Options for Deploying R Models in Production
Which Library Could Be Used to Make a Chord Diagram in R
Effectively Debugging Shiny Apps
How to Control Number of Minor Grid Lines in Ggplot2
Difference Between Subset and Filter from Dplyr
Creating Vector of Results of Repeated Function Calls in R
How to Optimize Read and Write to Subsections of a Matrix in R (Possibly Using Data.Table)