R 在Excel中像散点一样平滑(ggplot2+;plotly)

R 在Excel中像散点一样平滑(ggplot2+;plotly),r,ggplot2,plotly,R,Ggplot2,Plotly,我想用ggplot2和plotly模拟R中的Excel平滑样式 包裹 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

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

包裹

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)
我知道过度拟合是不好的,但我需要两条线直接通过点(如Excel)

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


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

您可以添加功能geom_xspline,如网站中所述:

然后使用代码:

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

p我在
ggalt
包中找到了
geomxspline()
的实现。它确实做到了我所需要的,因为Excel使用了Catmull Rom样条曲线平滑。因此,将
geom_xspline()
spline_shape=-0.5
一起使用可以完成这项工作。不幸的是,这个几何模型还没有在
plotly
中实现。这里的方法()是否适用于plotly?
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