Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 removes zero when using scale_x_sqrt

Tags:

r

ggplot2

When I plot data whose x coordinate starts with zero using ggplot2 and I use the scale_x_sqrt option, the plot starts from 1 on the x-axis instead of zero. If I add limits=c(-0.1, 100) I get an error that "NaNs produced". How can I get ggplot2 to include zero?

like image 751
Reza Avatar asked Dec 22 '17 17:12

Reza


People also ask

How do I stop Ggplot from scientific notation?

In case you want to omit the use of exponential formatting on one of the axes in a ggplot: Add scale_*_continuous(labels = scales::comma) with * being replaced by the axis you want to change (e.g. scale_x_continuous() ).

What is Scale_x_discrete in Ggplot?

scale_x_discrete() and scale_y_discrete() are used to set the values for discrete x and y scale aesthetics. For simple manipulation of scale labels and limits, you may wish to use labs() and lims() instead.

Does Ggplot remove missing values?

ggplot is somewhat more accommodating of missing values than R generally. For those stats which require complete data, missing values will be automatically removed with a warning. If na. rm = TRUE is supplied to the statistic, the warning will be suppressed.

How do I scale axis in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.


2 Answers

You can have the axis go down to zero with a square root transformation, but not below zero. The transformation produces imaginary values for x-values below zero.

library(tidyverse)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  scale_x_sqrt(limits=c(0,6), breaks=0:6, expand=c(0,0))

enter image description here

like image 55
eipi10 Avatar answered Nov 02 '22 17:11

eipi10


See: https://github.com/tidyverse/ggplot2/issues/980

The workaround they describe is:

library(ggplot2)
library(scales)
mysqrt_trans <- function() {
    trans_new("mysqrt", 
              transform = base::sqrt,
              inverse = function(x) ifelse(x<0, 0, x^2),
              domain = c(0, Inf))
}

ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  scale_x_continuous(trans="mysqrt", limits=c(0, NA))

In contrast to the other answers poster here this allows for some space to the left of zero.

enter image description here

like image 23
Nairolf Avatar answered Nov 02 '22 16:11

Nairolf