Scatter smooth like in Excel (ggplot2 + plotly)

时光怂恿深爱的人放手 提交于 2020-05-14 10:52:19

问题


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)


回答1:


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

Output will be:

Hope this helps!



来源:https://stackoverflow.com/questions/58352475/scatter-smooth-like-in-excel-ggplot2-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!