r - 在 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:有没有像“数学函数生成器”这样的东西可以帮助我了解与我在这张图中所做的绘制相关的函数?例如,我画了一个像上面这样的函数,应用程序为我生成了类似于这个形状/画的数学函数?
解决方案
这些曲线看起来像正切函数,所以:
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))
推荐阅读
- python - 如何更改google colab上使用的python版本
- docker-compose - 使用带有挂载到符号链接的 Docker 卷,但它也将数据持久化到主机。为什么?
- arrays - 角度迭代模型中的数组
- javascript - 当我发出发布请求时,React Native 返回 [未处理的承诺拒绝:TypeError:网络请求失败]
- mongodb - 在 mongodb 中使用聚合从两个集合中检索数据时出现问题
- python - 对内部 numpy 数组进行类迭代?任务?
- linux - 监控配置参数 - 组?
- javascript - 修复 React onDragExit 和 onDrop 事件在 Chrome 中不起作用
- html - 上传的图像未以 Safari 为中心
- reactjs - 错误:未捕获 [不变违规:对象作为 React 子对象无效