- R Data Visualization Recipes
- Vitor Bianchi Lanzetta
- 156字
- 2021-07-02 23:33:31
How to do it...
- Load ggplot2 and use geom_quatile() to draw quantile regression lines:
library(ggplot2)
ggplot( diamonds, aes( carat, price)) +
geom_point(shape = '.') +
geom_quantile(quantiles = c(.2, .4, .6, .8),
colour = 'blue', size = 1) +
ylim(0, max(diamonds$price))
Result is shown in the following image:

Figure 2.12 - A scatterplot with quantile regression lines.
- Before trying a similar result on plotly, start by fitting the quantile regression:
library(quantreg)
q20 <- fitted(rq( price ~ carat, data = diamonds, tau = .2))
q40 <- fitted(rq( price ~ carat, data = diamonds, tau = .4))
q60 <- fitted(rq( price ~ carat, data = diamonds, tau = .6))
q80 <- fitted(rq( price ~ carat, data = diamonds, tau = .8))
- Now it's possible to rely on plotly to draw quantile lines:
> library(plotly)
> c = I('black')
> plot_ly(ggplot2::diamonds, x = ~carat, y = ~price, type = 'scatter',
> mode = 'markers', marker = list(size = .8)) %>%
> add_lines(y = ~q20, color = c, marker = NULL) %>%
> add_lines(y = ~q40, color = c, marker = NULL) %>%
> add_lines(y = ~q60, color = c, marker = NULL) %>%
> add_lines(y = ~q80, color = c, marker = NULL) %>%
> layout(yaxis = list(range = c(0,20000)), showlegend = F)
Let's see how the events unfolded.