像Excel中一样平滑散布(ggplot2 +绘制)

时间:2019-10-12 08:55:22

标签: 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 

示例数据集

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)

我想要的

enter image description here

到目前为止我有什么

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

解决方案可能是纯图形的(比ggplotly()转换更具控制力。)

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

1 个答案:

答案 0 :(得分:0)

您可以添加站点中提到的geom_xspline函数: 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

输出将是: Plot Image

希望这会有所帮助!