首页 > 解决方案 > 在 ggplot 中使用 geom_function()

问题描述

这是我的数据框和我的 ggplot:

df_f <- tibble(
    seq_n = seq(1, 11, 1),
    top_white_values = c(1970, 1985, 1963, 1949, 1943, 1941, 1930, 1942, 1985, 1955, 1971)
)

ggplot(data = df_f) + 
    geom_point(aes(x = seq_n, y = top_white_values)) +
    geom_text(aes(x = seq_n, y = top_white_values, label = top_white_values))

我需要将按年份标记的点连接到 x 轴数字,但我需要使用geom_function(). 我想要一些圆角函数,如x^2, x^2, x^(1/2).

这是我想要达到的结果:

在此处输入图像描述

PS:有没有像“数学函数生成器”这样的东西可以帮助我了解与我在这张图中所做的绘制相关的函数?例如,我画了一个像上面这样的函数,应用程序为我生成了类似于这个形状/画的数学函数?

标签: rggplot2

解决方案


这些曲线看起来像正切函数,所以:

library(ggplot2)
df_f <- data.frame(
  seq_n = seq(1, 11, 1),
  top_white_values = c(1970, 1985, 1963, 1949, 1943, 1941, 1930, 1942, 1985, 1955, 1971)
)

my_tan <- function(x0, x1, y1){
  ymin <- layer_scales(last_plot())$y$range$range[1]
  ymax <- layer_scales(last_plot())$y$range$range[2]
  mult <- (ymax - ymin)/10
  function(x) mult * tan(pi/1.15 * (x - (x0 + x1) / 2) / (x1 - x0)) + (y1 + ymin)/2
}

plt <- ggplot(data = df_f) + 
  geom_point(aes(x = seq_n, y = top_white_values)) +
  geom_text(aes(x = seq_n, y = top_white_values, label = top_white_values))
plt + geom_function(fun = my_tan(3, 9, 1985), xlim = c(3, 9)) + 
  geom_function(fun = my_tan(9, 2, 1985), xlim = c(2, 9))

这使: 在此处输入图像描述


推荐阅读