Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 - Simple plot- cannot specify log axis limits

I'm trying to create a simple densityplot in R in ggplot2. Here's my code which works great.

d <-  ggplot(result, aes(x=result$baseMeanA)) 
d + geom_density(colour="darkgreen", size=2, fill="darkgreen") + 
scale_x_log10() + scale_y_continuous(limits = c(0, 0.45))

The problem is that I cannot adjust the x-axis as I would like, into negative numbers.

scale_x_log10(limits= c(1, 10000))

works great, but

scale_x_log10(limits= c(-1, 10000))

does not work at all! It gives me this error:

Error in if (zero_range(range)) { : missing value where TRUE/FALSE needed

Please help!

like image 531
user1678000 Avatar asked Sep 17 '12 15:09

user1678000


3 Answers

If the range of the limits should be partly below zero, you could log10-transform your variable and specify the limits for a continuous scale:

ggplot(result, aes(x=log10(baseMeanA))) +
   geom_density(colour="darkgreen", size=2, fill="darkgreen") + 
   scale_x_continuous(limits = c(-1, 10000) + 
   scale_y_continuous(limits = c(0, 0.45)) +
like image 114
Sven Hohenstein Avatar answered Sep 19 '22 05:09

Sven Hohenstein


What you are trying to do doesn't make much sense does it? The log of negative numbers isn't something we can represent in R

R> log(-1)
[1] NaN
Warning message:
In log(-1) : NaNs produced

so where should R draw the axis to?

like image 2
Gavin Simpson Avatar answered Sep 19 '22 05:09

Gavin Simpson


e^y cannot be negative. The exponential constant e is positive, and y is just an exponent. and by mathematical definition:

log(x) = y <==> x = e^y

This is precisely why R cannot calculate log(x) if x is negative. It just goes against the math definition.

I hope this helps understanding why this plot is giving you trouble.

like image 1
JAponte Avatar answered Sep 21 '22 05:09

JAponte