Excerise

Part 1: Using ggplotly() (a) Recall the Tuberculosis dataset from Week 2. It is provided to you as TB2020.csv, already in “tidy” form. Make a bar plot of total counts reported over the years in Australia, broken down by age and sex, and make it interactive using ggplotly(). Your plot should look something like this:

#加载包
library(dplyr)
## 
## 载入程序包:'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(here)
## here() starts at C:/Users/Winst/Desktop/DATA5002/lab/lab7
library(readr)
library(ggplot2)
library(plotly)
## 
## 载入程序包:'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
#加载数据并筛选出country == "Australia"
tb_oz <- read_csv(here("data", "TB2020.csv")) %>% 
  filter(country == "Australia")
## Rows: 40800 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): country, age_group, sex
## dbl (2): year, count
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#作图
p <- tb_oz %>% 
  #以性别分组
  group_by(sex, age_group) %>% 
  #计算人数总数
  summarise(count = sum(count)) %>%
  #横坐标为性别,纵坐标为人数,按年龄组分组
  ggplot(aes(sex, count, fill = age_group)) + 
  #直接使用y中的值,不堆叠分组
    geom_bar(stat = "identity", position = "dodge")
## `summarise()` has grouped output by 'sex'. You can override using the `.groups`
## argument.
ggplotly(p)
  1. Recall the problem of looking at a player’s “productivity” in terms of number of points scored per minute on the court and the amount of time they are allocated on the court. Produce an interactive plot. Your result should look (and act) something like this:
scoring_rate <- read.csv("scoring_rate.csv")
p <- scoring_rate %>% 
  ggplot(aes(
    x = Minutes, 
    y = Scored / Minutes,
    #%s表示插入字符串,%d表示插入整数,%1.1f表示插入浮点数,保留一位小数,%2.2f 表示插入浮点数,保留 2 位小数
    text = sprintf(
      "%s (%d)
      Time on court: %1.1f minute(s)
      Scoring rate: %2.2f points/minute", 
      Player, Season, Minutes, Scored/Minutes
    ))) +
  geom_point(size = 0.5) + 
  labs(x = "Time on court (minutes)",
       y = "Productivity (points per minute)")
#tooltip = "text" 指定使用 aes(text) 中定义的内容作为鼠标悬停时的提示信息
ggplotly(p, tooltip = "text")

Part 2: Using plot_ly() (a) Re-create the visualisation in 1(b) using the plot_ly function instead of ggplotly.

scoring_rate_plot_data <- scoring_rate %>%
  mutate(Scoring_Rate = Scored/Minutes)
  
p <- plot_ly(
  data = scoring_rate_plot_data,
  #横轴变量,数轴变量,输出形式为散点图
  x = ~Minutes, y = ~Scoring_Rate, type = "scatter")
p
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning: Ignoring 6 observations
  1. Try various customisations from the plotly documentation: https://plotly.com/r/line-and-scatter/
scoring_rate_plot_data <- scoring_rate_plot_data %>%
  #将时间分为10年前,10年后
  mutate(Decade = case_when( Season < 2010 ~ "2000s",
                             Season >= 2010 ~ "2010s"))


p <- plot_ly(
  data = scoring_rate_plot_data,
  x = ~Minutes, y = ~Scoring_Rate, 
  #增加按世纪分颜色,颜色设置
  color = ~Decade, colors = "Set1",
  type = "scatter", alpha = 0.5
)
p
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning: Ignoring 6 observations

Part 3: Dashboard (a) Create a simple (if rather clunky) dashboard for exploring the Tuberculosis data used in Week 2 over a range of countries and years. We’ll start by using plotly and crosstalk to produce filtered time trends. (Note: To make it run faster on slower PCs, only countries whose names begin with “A” are included.)

tb_A <- read_csv(here("data", "TB2020.csv")) %>% 
  #筛选出国家名称以字母 “A” 开头的记录
  filter(startsWith(country, "A"))
## Rows: 40800 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): country, age_group, sex
## dbl (2): year, count
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
library(crosstalk)
#dashboard包数据导入
d <- SharedData$new(tb_A)

bscols(widths = c(2, NA),
       list(
         #生成复选框过滤器,允许按性别(sex)或年龄组(age_group)进行筛选
         filter_checkbox("sex", "Sex", d, ~sex, inline = TRUE),
         filter_checkbox("age_group", "Age Group", d, ~age_group),
         #生成一个滑动条过滤器,允许选择年份范围
         filter_slider("year", "Year", d, ~year, width = "100%"),
         #生成一个下拉菜单过滤器,允许选择具体的国家,不允许多选
         filter_select("country", "Country", d, ~country, multiple = FALSE)
       ),
       #作图,点图,添加线及标记,标记大小为10
       plot_ly(d, x = ~year, y = ~count, color = ~age_group, 
               symbol = ~sex, type = "scatter", 
               mode = "lines+markers", marker = list(size = 10)))

Part 4: Crosstalk Take the same interactive graph as in Part 2. Now, augment it with linked bar plots showing the total number of cases over the period, grouped either by sex or by age:

d <- SharedData$new(tb_A)
bscols(widths = c(2,NA),
        list(
          #inline true所有复选框会在 同一行 中水平排列(紧凑)
          filter_checkbox("sex", "Sex", d, ~sex, inline = TRUE),
          filter_checkbox("age_group", "Age Group", d, ~age_group),
          filter_slider("year", "Year", d, ~year, width = "100%"),
          filter_select("country", "Country", d, ~country, multiple = FALSE)
        ),
       list(
         plot_ly(d, x = ~year, y = ~count, color = ~age_group, 
                 symbol = ~sex, type = "scatter", 
                 mode = "lines+markers", marker = list(size = 10)),
         #增加两张条形图,按颜色或按年龄分
         plot_ly(d, x = ~age_group, y = ~count, color = ~sex, type = "bar"),
         plot_ly(d, x = ~sex, y = ~count, color = ~age_group, type = "bar")
       ))
## Warning: Ignoring 642 observations
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning: Ignoring 642 observations

Part 5: ggiraph (a) Create a time series graph of Tuberculosis by age group. When the user hovers over a particular line, that line should be highlighted by: increasing the width of the highlighted line, and increasing the transparency of the non-highlighted lines.

#ggiraph 创建了一个带有交互功能的线图
library(ggiraph)
#
gg <- ggplot(tb_oz, aes(x = year, y = count, 
                        #按 age_group 对线条分组并使用不同颜色
                        colour = age_group, group = age_group)) +
  #定义鼠标悬停时显示的提示信息(age_group),分配唯一标识符给每条线,用于实现交互
  geom_line_interactive(aes(tooltip = age_group, data_id = age_group)) +
  #使用 viridis 调色板为不同的年龄组分配颜色
  scale_color_viridis_d() + 
  labs(title = "move mouse over lines")
#转换为交互式图表,设置长宽
x <- girafe(ggobj = gg, width_svg = 8, height_svg = 6,
            
  options = list(
    #设置非悬停元素的样式:透明度降低至 0.1
    opts_hover_inv(css = "opacity:0.1;"),
    #设置悬停元素的样式:线条宽度增加至 2
    opts_hover(css = "stroke-width:2;")
  ))
x

Part 6: Combining plots (Optional) (a)Recall the Iris dataset. Create a pairwise plot of all of the measurements, colour-coded by species, such that selecting points (with the lasso or box select tool) will highlight those points on all of the corresponding plots.

Note: this question uses the function highlight_key(), which has limited documentation, and is most likely a deprecated function. Some students have found that these graphs do not work on their machines.

library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
#将 iris 数据框包装为一个可以与 plotly 高亮功能兼容的对象
highlight_key(iris) %>%
  #ggpairs用于创建变量之间成对关系的图矩阵,选择数据框前4列
  ggpairs(aes(colour = Species, alpha = I(.7)), columns = 1:4) %>%
  #将x,y,颜色转换为可交互式图标
  ggplotly(tooltip = c("x", "y", "colour")) %>%
  #添加高亮
  highlight("plotly_selected")
## Warning: Can only have one: highlight
## Warning: Can only have one: highlight
## Warning: Can only have one: highlight
## Setting the `off` event (i.e., 'plotly_deselect') to match the `on` event (i.e., 'plotly_selected'). You can change this default via the `highlight()` function.
  1. Modify the above plot so that clicking on a point now selects its whole Species on all plots.
highlight_key(iris, ~Species) %>%
  ggpairs(aes(group = Species, colour = Species, 
              alpha = I(.7)), columns = 1:4) %>%
  ggplotly(tooltip = c("x", "y", "colour"))
## Warning: Can only have one: highlight
## Warning: Can only have one: highlight
## Warning: Can only have one: highlight