R Data Visualization Recipes
上QQ阅读APP看书,第一时间看更新

How it works...

Following steps are crafting alternative visualization to dot plots using ggvis, plotly, and ggplot2:

  1. Coerce the Salaries$rank categories into integers, plus add some jitter to them:
> set.seed(10)
> library(car)
> dt <- Salaries
> dt$rk <- 3 + runif(length(dt$rank),
max = .2, min = -.2)
> dt$rk[dt$rank == 'AssocProf'] <- dt$rk[dt$rank == 'AssocProf'] - 1
> dt$rk[dt$rank == 'AsstProf'] <- dt$rk[dt$rank == 'AsstProf'] - 2
  1. Using ggvis, trust layer_points() to add the points and add_axis() to take care of adjusting the labels:
> library(ggvis)
> dt %>% ggvis(x = ~rk, y = ~salary) %>%
layer_points(opacity := .3) %>%
add_axis('x',values = c(1,1), title = '',
properties = axis_props(labels = list(text = 'Assistant Professor'))) %>%
add_axis('x',values = c(2,2), title = '',
properties = axis_props(labels = list(text = 'Associated Professor'))) %>%
add_axis('x',values = c(3,3), title = 'Rank',
properties = axis_props(labels = list(text = 'Professor')))

Final result looks like the following image:

Figure 3.8: Plotting points with ggvis

  1. plotly can also draw similarly; layout() takes care of the x-axis labels:
 > plot_ly(dt, x = ~rk, y =~salary , type = 'scatter', 
mode = 'markers', alpha =.4) %>%
layout(xaxis = list(tickvals = c(1,2,3),
ticktext = c('Assistant Professor',
'Associated Professor',
'Professor')))
  1. ggplot2 can do the same using geom_jitter(); jittered data is not needed:
> library(ggplot2)
> ggplot(Salaries, aes(x = rank, y = salary)) +
geom_jitter(alpha = .4, height = 0,
width = .3)

Let's see how these unfolded.