像 Excel 中一样平滑散布(ggplot2 + plotly)平滑、Excel、plotly

2023-09-07 08:43:55 作者:别人家的孩子.

我想在 R 中使用 ggplot2 和 plotly 来模仿 Excel 平滑样式.

库(dplyr)图书馆(小标题)图书馆(ggplot2)图书馆(情节)library(ggforce) #only for geom_bspline() 在下面的例子中(可以使用其他平滑函数)library(scales) #only for percent() 格式如下
ggplot2

示例数据集

df <- tibble(Group = rep(LETTERS[1:2], each = 10),x = 代表(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), 标签 = scales::percent) +scale_x_continuous(breaks = 1:10, minor_breaks = NULL) +主题_minimal()) %>%ggplotly()

我知道过度拟合不好,但我需要两条线直接穿过点(就像在 Excel 中一样).

解决方案可能是纯情节(比 ggplotly() 转换提供更多控制).

附加,不需要:仅显示点的标签(非平滑曲线)

解决方案

可以添加geom_xspline函数,网站中提到:

希望这会有所帮助!

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

Packages

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 

Example dataset

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)

What I want

What I have so far

(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()

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

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

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

解决方案

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/

After that use the code:

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)) +
  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

Output will be:

Hope this helps!