Overlayed density plots
In this exercise, you will learn how to create density plots and overlay them to compare the distribution of critic scores for three video game publishers: Activision, Electronic Arts, and Nintendo.
To create a density plot for Critic_Score
, store the results of the density()
command, and then pass the x
and y
coordinates to add_lines()
:
d <- density(vgsales2016$Critic_Score, na.rm = TRUE)
plot_ly() %>%
add_lines(x = ~d$x, y = ~d$y, fill = 'tozeroy') %>%
layout(xaxis = list(title = 'Critic score'),
yaxis = list(title = 'Density'))
Notice how you can create new plot types easily using familiar code! The fill = 'tozeroy'
argument fills the area under the curve.
Data frames activision
,ea
, and nintendo
are loaded, as is plotly
.
This exercise is part of the course
Interactive Data Visualization with plotly in R
Exercise instructions
- Compute density curves of
Critic_Score
for Activision, EA, and Nintendo, storing them in thed.a
,d.e
, andd.n
objects, respectively. - Create overlayed density plots of
Critic_Score
foractivision
,ea
, andnintendo
(in that order).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Compute density curves
d.a <- density(___, na.rm = TRUE)
d.e <- density(___, na.rm = TRUE)
d.n <- density(___, na.rm = TRUE)
# Overlay density plots
plot_ly() %>%
add_lines(x = ___, y = ___, name = "Activision", fill = 'tozeroy') %>%
add_lines(x = ___, y = ___, name = "Electronic Arts", fill = 'tozeroy') %>%
add_lines(x = ___, y = ___, name = "Nintendo", fill = 'tozeroy') %>%
layout(xaxis = list(title = 'Critic Score'),
yaxis = list(title = 'Density'))