5

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!

2
  • 1
    Just guessing, but perhaps you want the limits on the original scale to go from 0.1 to 10000 (i.e. log10(x) goes from -1 to 5) ? Presumably you don't want log10(x) to go from -1 to 10000, because the upper limit would then be at 10^10000 (a very large value, since there are about 10^80 atoms in the observable universe en.wikipedia.org/wiki/Observable_universe ... ) If I'm right, then you want scale_x_log10(limits=c(0.1,1e5)) Commented Sep 17, 2012 at 18:38
  • Yes I think I understand now. I can't use negative numbers in a log scale.. Thank you. I see now what I need to do, I need to add a pseudonumber like 1 or 0.1 to the result, so that it visually will look correct, otherwise I will loose all the very small numbers somehow. Commented Sep 18, 2012 at 8:27

3 Answers 3

5

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)) +
Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

Yes, you are right probably. I did not know that. I think I know now that to solve my problem I need to add a pseudonumber to my result so that I visually can look at it.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.