【发布时间】:2023-01-07 00:39:58
【问题描述】:
我有几个变量的函数 H(x,y,z,w)=2xy+3zw-x^2+W^3。我需要绘制当 z=3 和 w=5 时函数 H 相对于 x 和 y 的等高线图。对于使用 R 绘制此等高线图的任何帮助,我们将不胜感激。谢谢!
【问题讨论】:
标签: r function ggplot2 plot contourf
我有几个变量的函数 H(x,y,z,w)=2xy+3zw-x^2+W^3。我需要绘制当 z=3 和 w=5 时函数 H 相对于 x 和 y 的等高线图。对于使用 R 绘制此等高线图的任何帮助,我们将不胜感激。谢谢!
【问题讨论】:
标签: r function ggplot2 plot contourf
您可以创建 x 和 y 的序列并计算函数:
library(ggplot2)
#Create the function
H <- function(x, y, z = 3, w = 5) 2*x*y + 3*z*w - x^2 + w^3
#Sequence of x and y
s <- seq(-100, 100, length.out = 100)
#Grid
g <- expand.grid(x = s, y = s)
#Compute for each value of x and y the function H
g$value <- with(g, H(x, y))
#Plot
ggplot(g) +
aes(x = x, y = y, z = value) +
geom_contour()
#With some customization
library(geomtextpath)
ggplot(g) +
aes(x = x, y = y, z = value) +
geom_textcontour(size = 2, color = "blue")
【讨论】:
允许看到 H 级别的替代方法是:
library(ggplot2)
library(geomtextpath)
H <- function(x, y, z = 3, w = 5) 2 * x* y + 3 * z * w - x^2 + w^3
df <- expand.grid(x = seq(0, 100), y = seq(0, 100))
df$H <- H(df$x, df$y)
ggplot(df, aes(x, y, z = H)) +
geom_textcontour(aes(label = after_stat(level))) +
coord_equal(xlim = c(0, 100)) +
theme_minimal() +
theme(panel.border = element_rect(fill = NA, linewidth = 1),
panel.grid = element_blank())
【讨论】: