简体   繁体   English

用ggplot2绘制数学函数

[英]Plotting math function with ggplot2

Following code plots a math function as a heatmap (from: How to plot a maths function as a heatmap ): 以下代码将数学函数绘制为热图(来自: 如何将数学函数绘制为热图 ):

xvec <- yvec <- seq(0,10,length.out=41)
z <- outer(xvec,yvec,function(x,y) x*y^2)
image(xvec,yvec,z)

How can I create this using ggplot2 geom_tile() ? 如何使用ggplot2 geom_tile()创建此对象?

Following commands do not work: 以下命令不起作用:

ggplot()+geom_tile(aes(x=xvec, y=yvec, z=z))

and

zdf = data.frame(z)
ggplot(zdf)+geom_tile(aes(z=zdf))

I am surprised not to find similar question on searching. 我很惊讶没有在搜索中找到类似的问题。 Thanks for your help. 谢谢你的帮助。

You need to arrange the X/Y coordinates and the data ( z in your case) into a data.frame instead of a matrix. 您需要将X / Y坐标和数据(在您的情况下为zdata.framedata.frame而不是矩阵中。

For example: 例如:

xvec <- yvec <- seq(0,10,length.out=41)
df <- expand.grid(xvec, yvec)
df$z <- apply(df, 1, function(p) p[1] * p[2]^2)

head(df)

#   Var1 Var2 z
# 1 0.00    0 0
# 2 0.25    0 0
# 3 0.50    0 0
# 4 0.75    0 0
# 5 1.00    0 0
# 6 1.25    0 0

library(ggplot2)
ggplot(df) + geom_tile(aes(x=Var1, y=Var2, fill=z))

And you get: 你会得到:

在此处输入图片说明

You could also reshape your outer results with 您还可以通过以下方式重塑outer结果

xvec <- yvec <- seq(0,10,length.out=41)
z <- outer(xvec,yvec,function(x,y) x*y^2)

ggplot(data.frame(xvec=xvec[row(z)], yvec=yvec[col(z)], z=as.numeric(z))) + 
    geom_tile(aes(x=xvec, y=yvec, fill=z))

What we are doing here is building a new data.frame with triplets of values to plot: (x,y,color). 我们在这里正在构建一个新的data.frame,其中包含三元组的值以绘制:(x,y,color)。 The problem is we have length(xvec) rows and length(yvec) columns but length(xvec) * length(yvec) actual observations. 问题是我们有length(xvec)行和length(yvec)列,但是length(xvec) * length(yvec)实际观测值。 So this trick will repeat the row and column values to make them the same length as the z values. 因此,此技巧将重复行和列的值,以使其长度与z值相同。 Since z is a matrix, row(z) will give the row number for each value in z . 由于z是一个矩阵, row(z)将给予中的每个值的行号z We use this to repeat the xvec values multiple times and keep them insync with the z values. 我们使用它重复xvec值多次,并使它们与z值不同步。 Same goes for the yvec values but we match those up to the columns of z . yvec值也一样,但我们将其匹配到zcolumns This is another way to create a data.frame in the form 这是创建以下形式的data.frame的另一种方法

  xvec yvec z
1 0.00    0 0
2 0.25    0 0
3 0.50    0 0
4 0.75    0 0
5 1.00    0 0
6 1.25    0 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM