像Excel中一样平滑地散布(ggplot2 +绘图) [英] Scatter smooth like in Excel (ggplot2 + plotly)

查看:227
本文介绍了像Excel中一样平滑地散布(ggplot2 +绘图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot2和plotly模拟R中的Excel平滑样式.

I would like to mimic Excel smoothing style in R using ggplot2 and plotly.

包裹

library(dplyr)
library(tibble)
library(ggplot2)
library(plotly)
library(ggforce) #only for geom_bspline() in example below (other smoothing functions can be used)
library(scales) #only for percent() formatting below 

示例数据集

df <- tibble(Group = rep(LETTERS[1:2], each = 10),
             x = rep(1:10, 2),
             y = c(2, 5, 9, 15, 19, 19, 15, 9, 5, 2,
                   1, 0, 3, 2, 3, 4, 14, 24, 24, 25)*0.01)

我想要的

到目前为止我有什么

(df %>%
    ggplot(aes(x, y)) +
    geom_point(aes(color = Group)) +
    ggforce::geom_bspline(aes(group = Group, color = Group)) +
    scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) +
    scale_x_continuous(breaks = 1:10, minor_breaks = NULL) +
    theme_minimal()) %>%
  ggplotly()

我知道过度拟合是不好的,但是我需要两条直线都可以直通各个点(例如在Excel中).

I know that overfitting is bad, but I need both lines to go straight through points (like in Excel).

解决方案可能是纯图形的(比ggplotly()转换具有更多的控制权).

Solution might be pure plotly (gives more control than ggplotly() transformation).

其他,不是必需的:仅显示点标签(不显示平滑曲线)

Additional, not required: Display Labels for points only (not smoothed curve)

推荐答案

您可以添加站点中提到的geom_xspline函数: https://www.r-bloggers.com/roll-your-own-stats-and-geoms-in-ggplot2-part-1-splines/

You can add the function geom_xspline, mentioned in the site: https://www.r-bloggers.com/roll-your-own-stats-and-geoms-in-ggplot2-part-1-splines/

之后使用代码:

p <- ggplot(df, aes(x, y, group=Group, color=factor(Group))) +
  geom_point(color="black") +
  geom_xspline(size=0.5)+
  geom_point(aes(color = Group)) +
  geom_xspline(aes(group = Group, color = Group)) +
  scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) +
  scale_x_continuous(breaks = 1:10, minor_breaks = NULL) +
  theme_minimal()+
  geom_text(aes(label=y),hjust=1, vjust=-1)
p

输出将是:

希望这会有所帮助!

这篇关于像Excel中一样平滑地散布(ggplot2 +绘图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆