## set up code
# load libraries
library(googlesheets4)
library(tidyverse)
library(socsci)
library(plotly)
library(ggplot2)
library(coolorrr)
# load dataset
url <- "https://docs.google.com/spreadsheets/d/1npon5F_Gr40HQj8KVeHq_un7SOep4dzc6kjP0px7nLo/edit?usp=sharing"
gs4_deauth()
dt <- range_speedread(url)Graph Challenge 9
The {plotly} package lets you turn your ggplot figures into interactive ones. You can learn more about it here: https://plotly.com/ggplot2/
For this graph challenge, I want you to create an interactive plot with the April 2025 DU survey data using ggplot and plotly. The type of plot is up to you. So is the variable or variables you’d like to show.
When you’re done, rather than hitting the “render” button, hit the “publish” button to publish your submission to RPubs. Then, submit the link to your publication on Canvas.
## data work
# look at data
# glimpse(dt)
# select variable (question 2: Some people don't pay much attention to political campaigns. How interested have you been in politics and the political campaigns so far this year?)
dt |>
select(Q2) |>
slice_head(n = 6)# A tibble: 6 × 1
Q2
<dbl>
1 1
2 4
3 4
4 1
5 4
6 1
# remove na values
dt |>
mutate(
across(
Q2,
~ replace_na(.x, 0)
)
) -> dt## create plot
# color palette
colors <- c(
"Extremely interested" = "#b8d0e8",
"Very Interested" = "#cae5ff",
"Moderately Interested" = "#acedff",
"Slightly Interested" = "#89bbfe",
"Not interested at all" = "#6f8ab7",
"Undecided" = "#615d6c"
)
# create normal plot
plot <- dt |>
pivot_longer(Q2) |>
mutate(
name = rep(
c("Extremely interested",
"Very Interested",
"Moderately Interested",
"Slightly Interested",
"Not interested at all",
"Undecided"),
len = n()
),
name = factor(name, levels = c(
"Extremely interested",
"Very Interested",
"Moderately Interested",
"Slightly Interested",
"Not interested at all",
"Undecided"
))
) |>
group_by(name) |>
ct(value) |>
filter(value == 1) |>
ggplot() +
aes(
x = name,
y = pct,
fill = name
) +
geom_col() +
labs(
x = NULL,
y = NULL,
title = "Percentage of students interested in political campaigns"
) +
scale_y_continuous(
labels = scales::percent
) +
scale_fill_manual(values = colors) +
theme(
axis.text.x = element_text(
angle = 45,
hjust = 1
),
legend.position = "none"
)
# create interactive plot using plotly
ggplotly(plot)Sources: https://drive.google.com/file/d/1ga7g1WRCrAuy-PO6_73kAUyj20LNMPVM/view https://plotly.com/ggplot2/ https://docs.google.com/spreadsheets/d/1npon5F_Gr40HQj8KVeHq_un7SOep4dzc6kjP0px7nLo/edit?usp=sharing