Home > OS >  How can I draw a scatter plot with a stairstep line?
How can I draw a scatter plot with a stairstep line?

Time:06-22

So, while I'm trying to mimic a enter image description here

Any help would be appreciated. Thanks in advance.

CodePudding user response:

I guess it was done something like this:

library(tidyverse)

ggplot(diamonds, aes(price, carat))  
  geom_point(aes(color = cut))  
  scale_color_brewer(palette = "Pastel1")  
  theme_minimal()  
  geom_step(data = diamonds %>%
              mutate(breaks = cut(price, breaks = 7)) %>%
              group_by(breaks) %>%
              summarize(carat = mean(carat),
                        price = range(price)),
            color = "green2", size = 1.5)

Created on 2022-06-22 by the reprex package (v2.0.1)

CodePudding user response:

The web app is a little bit confusing, because stepwise regression usually refers to feature selection in a linear model. However, you can get the steps by grouping the data and summarizing the groups to be plotted with geom_step e.g. to have 5 equidistant intervals:

library(tidyverse)

n_intervals <- 5

diamonds %>%
  arrange(price) %>%
  mutate(group = cut(price, n_intervals   1)) %>%
  group_by(group) %>%
  summarise(price = mean(price), carat = mean(carat)) %>%

  ggplot(aes(price, carat))  
    geom_step()

Created on 2022-06-22 by the reprex package (v2.0.0)

  • Related