R ggplot2 - Simple plot- cannot specify log axis limits

时间秒杀一切 提交于 2021-02-07 14:20:35

问题


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!


回答1:


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)) +



回答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?




回答3:


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.



来源:https://stackoverflow.com/questions/12462479/r-ggplot2-simple-plot-cannot-specify-log-axis-limits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!