使用对数刻度的stat_function在R中绘图 [英] Plotting in R using stat_function on a logarithmic scale

查看:268
本文介绍了使用对数刻度的stat_function在R中绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R的 ggplot2 中遇到了严重的问题,试图让我的头在 stat_function 的范围内。我从这个简单的例子开始:

pre $ g $ pggplot(data.frame(x = c(1,1e4)),aes( x))+ stat_function(fun = function(x)x)

不幸的是,当我为x轴和y轴添加对数标度时,如此:

  ggplot(data.frame(x = 1:1e4 ),aes(x))+ 
scale_x_log10()+
scale_y_log10()+
stat_function(fun = function(x)x)

我得到以下结果,这是对身份函数的一个非常讨厌的违反。



是有什么非常基本的,我错过了?那么什么是正确和最简单的方式来绘制日志规模的功能?



编辑:
灵感来自答案I继续尝试使用比例尺和美学参数。

  ggplot(data.frame(x = 1:1e4,y = 1:1e4),aes(x,y))+ 
scale_x_log10()+
scale_y_log10()+
stat_function(fun = function(x)x)

带有一个明显未使用的y值向量(未被 stat_function 就是)。轴转换是否依赖于数据的可用性?

解决方案当您使用 scale_x_log10() code>然后 x 值进行对数转换,然后用于计算 y 值,其中 stat_function()。然后将 x 值返回转换为原始值以进行缩放。 y 的值仍然是从转换后的 x 的计算结果。您可以通过绘制不含 scale_y_log10()的值来检查。

  ggplot(data.frame(x = 1:1e4),aes(x))+ 
stat_function(fun = function(x)x)+
scale_x_log10()

如果你应用 scale_y_log10(),你已经计算出了 y 值,所以曲线被绘制出来。


I'm having serious problems trying to get my head around stat_function in R's ggplot2. I started off with this trivial example:

ggplot(data.frame(x = c(1, 1e4)), aes(x)) + stat_function(fun = function(x) x)

which works as expected. Unfortunately, when I add log scales for both x and y axes so:

ggplot(data.frame(x = 1:1e4), aes(x)) +
  scale_x_log10() + 
  scale_y_log10() +
  stat_function(fun = function(x) x)

I get the following result, which is a pretty nasty violation of the identity function.

Is there something very basic that I'm missing? What is then the correct and least hacky way to plot a function on log scale?

EDIT: Inspired by the answers I went on and experimented with scales and the aesthetics parameter. I was even more puzzled to find out that I got what I expected using the code below:

ggplot(data.frame(x = 1:1e4, y = 1:1e4), aes(x, y)) +
  scale_x_log10() + 
  scale_y_log10() +
  stat_function(fun = function(x) x)

with an apparently unused vector of y values (unused by stat_function that is). Do the axis transformations depend on the availability of data?

解决方案

When you use scale_x_log10() then x values are log transformed, and only then used for calculation of y values with stat_function(). Then x values are backtransformed to original values to make scale. y values remain as calculated from log transformed x. You can check this by plotting values without scale_y_log10(). In plot there is straight line.

ggplot(data.frame(x=1:1e4), aes(x)) +
    stat_function(fun = function(x) x) +
    scale_x_log10() 

If you apply scale_y_log10() you log transform already calculated y values, so curve is plotted.

这篇关于使用对数刻度的stat_function在R中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆