在ggplot中绘制二维函数

时间:2018-05-15 21:51:18

标签: r ggplot2

我想绘制一个带有两个参数的函数。到目前为止我发现的最好的是image功能,但是我喜欢找到更好的3D情节或更好的ggplot countour情节:

x_seq = seq(1,1000)

y_seq = seq(1,5000)

z = outer(contributor_idx, size_estimate, function(x,y) log(y+1) + log(y+1)/log(x+1))

image(z)

current image

2 个答案:

答案 0 :(得分:3)

这是一个ggplot版本:

library(tidyverse)

# Every 5th value to reduce plotting time for the example
x_seq = seq(1,1000,5)
y_seq = seq(1,5000,5)

z = outer(x_seq, y_seq, function(x,y) log(y+1) + log(y+1)/log(x+1))

colnames(z) = y_seq
rownames(z) = x_seq

# Convert to long format, convert row and column values to numeric, and create groups for colors
dat = as.data.frame(z) %>% 
  rownames_to_column(var="x_seq") %>% 
  gather(y_seq, value, -x_seq) %>% 
  mutate(y_seq=as.numeric(y_seq), 
         x_seq=as.numeric(x_seq),
         value_range = cut(value, 8))

ggplot(dat, aes(x_seq, y_seq, fill=value_range)) + 
  geom_raster() +
  scale_fill_manual(values=colorRampPalette(c("red","orange","yellow"))(8)) +
  theme_classic() +
  guides(fill=guide_legend(reverse=TRUE))

enter image description here

你也可以做一个平滑的色彩渐变,但在这种情况下,它没有足够的对比度来照亮。

ggplot(dat, aes(x_seq, y_seq, fill=value)) + 
  geom_raster() +
  scale_fill_gradient(low="red", high="yellow") +
  theme_classic()

enter image description here

答案 1 :(得分:2)

plotly非常支持绘制曲面(无论如何都能以更好的交互方式工作):

library(plotly)

df <- data.frame(x = seq(500),
                 y = seq(500))

z <- outer(df$x, df$y, function(x, y) log(y + 1) + log(y + 1) / log(x + 1))

plot_ly(df, x = ~x, y = ~y, z = ~z) %>% 
    add_surface()

plotly surface