Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatter smooth like in Excel (ggplot2 + plotly)

Tags:

r

ggplot2

plotly

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

enter image description here

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)

like image 829
Matiasko Avatar asked Jun 12 '26 01:06

Matiasko


1 Answers

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: Plot Image

Hope this helps!

like image 198
abhisekG Avatar answered Jun 16 '26 16:06

abhisekG