简体   繁体   English

如何在 R 和 ggplot2 中绘制等于 0 的二元函数?

[英]How do I plot a bivariate function equated to 0 in R and ggplot2?

I am trying to plot a bivariate function equated to 0 in R, using no packages other than the basic packages and ggplot2 .我试图在 R 中绘制一个等于 0双变量函数,除了基本包和ggplot2之外不使用任何包。 Namely, the function is:即,函数是:

f(x,y) = x-log(x)+y-log(y)+C, where C < -2 f(x,y) = x-log(x)+y-log(y)+C,其中 C < -2

Can I plot this function equated to 0, using R?我可以使用 R 绘制这个等于 0 的函数吗? . . I did this using Desmos online graphing calculator and it worked, but now I can't figure out how to do it in R. I don't need the exact solution of x and y, but just the plot.我使用Desmos 在线图形计算器完成了此操作并且它有效,但现在我无法弄清楚如何在 R 中执行此操作。我不需要 x 和 y 的精确解,只需要绘图。

Here's a quick brute force approach:这是一个快速的蛮力方法:

library(tidyverse)

my_func <- function(x, y, C) { x - log(x) + y - log(y) + C }

expand_grid(x = seq(0, 15, by = 0.02),
            y = seq(0, 15, by = 0.02),
            C = seq(-10, -2, by = 1)) %>%
  mutate(error = my_func(x, y, C)) %>%
  filter(abs(error) < 0.1) %>%
  ggplot(aes(x, y, alpha = 1 - abs(error))) +
  geom_tile() +
  guides(alpha = F) +
  facet_wrap(~C)

在此处输入图片说明


EDIT: version using ggplot2 with base R.编辑:使用ggplot2和基础 R 的版本。

library(ggplot2)
output <- expand.grid(x = seq(0, 15, by = 0.02),
            y = seq(0, 15, by = 0.02),
            C = seq(-10, -2, by = 1))
output$error = my_func(output$x, output$y, output$C)
output <- output[abs(output$error) < 0.1,]
ggplot(output, aes(x, y, alpha = 1 - abs(error))) +
  geom_tile() +
  guides(alpha = F) +
  facet_wrap(~C)

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

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