class: center, middle, inverse, title-slide .title[ # 量化金融与金融编程 ] .subtitle[ ## L02 ggplot2 数据可视化 ] .author[ ###
曾永艺 ] .institute[ ### 厦门大学管理学院 ] .date[ ###
2023-09-22 ] --- class: middle, hide_logo background-image: url(imgs/logo-ggplot2.png) background-size: 10em background-position: 90% 50%
-- - ## .font120[
] 的绘图系统 -- - ## `ggplot2` 入门 - ### The Layered Grammar of Graphics - ### 将数据映射为几何对象的图形属性 - ### 统计变换、位置调整、坐标、分面 - ### 标签、标注、标度、主题等 -- - ## `ggplot2` extensions --- ### 一图胜千言 <img src="L02_Visualization_files/figure-html/datasaurus-1.png" width="85%" style="display: block; margin: auto;" /> --- class: inverse, center, middle # 1. .font120[
] 的绘图系统 --- ### .font120[
] 的绘图系统 <img src="imgs/RGraphics-fig1.14-R-graphics-system.png" width="58%" style="display: block; margin: auto;" /> --- ### .font120[
] 基础绘图系统:`graphics`包 .pull-left[ - .font120[高阶绘图函数] - **`plot()`** - `barplot()`、`pie()`、`dotchart()`、`boxplot()`、`hist()`、 `stripchart()`、`stem()`、`smoothScatter()`、`spineplot()`、 `mosaicplot()`、`pairs()`、`matplot()`、`image()`、 `contour()`、`persp()` …… - .font120[低阶绘图函数] - `points()`、`lines()`、`segments()`、`arrows()`、`xspline()`、`rect()`、`polygon()`、`polypath()`、`rasterImage()`、`title()`、`text()`、`legend()` 等 ] -- .center[示例] .pull-right[ .code70[ ```r EUSM <- window(EuStockMarkets, 1992, 1994) plot(EUSM[, "FTSE"], ylim = range(EUSM), xlab = "Time", ylab = "Price", adj = 1, cex.main = 1.5) lines(EUSM[, "DAX"], lty = "dashed") title(main = "Index's Price") legend(1992, 3450, c("FTSE", "DAX"), lty = c("solid", "dashed"), bty = "n") ``` <img src="L02_Visualization_files/figure-html/EUSM-1.png" style="display: block; margin: auto;" /> ] ] --- class: inverse, center, middle background-image: url(imgs/logo-ggplot2.svg) background-size: 12% background-position: 18% 50% # 2. `ggplot2`<sup>.font60[v3.4.3]</sup> 入门 --- layout: true ### .bold[2.1 The Layered Grammar of Graphics] --- -- .font130[_Data Visualization_:将.bold[数据]映射为.bold[几何对象的美学属性]] .font110[ - 数据(.red[data]):我们想要可视化的对象,包含变量 - 几何对象(.red[geom]etries):用来呈现数据的几何图形对象,如点、条形、线条等 - 美学属性(.red[aes]thetic):几何对象的视觉属性,如`x`坐标和`y`坐标位置、颜色、形状等 ] <img src="imgs/visualization-stat-point.png" width="100%" style="display: block; margin: auto;" /> --- .font130[`ggplot2` 的语法模板] .code150[ ```r *ggplot(data = <DATA>) + * <GEOM_FUNCTION>( * mapping = aes(<MAPPINGS>), stat = <STAT>, position = <POSITION> ) + <COORDINATE_FUNCTION> + <FACET_FUNCTION> ``` ] --- layout: true ### .bold[2.2 将.red[数据]映射为几何对象的美学属性] --- ```r library(tidyverse) ``` -- ```r mpg # print(mpg) ``` ``` #> # A tibble: 234 × 11 #> manufacturer model displ year cyl trans drv cty hwy fl class #> <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> #> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact #> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact #> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compact #> # ℹ 231 more rows ``` -- ```r # 查看ggplot2包内置数据集mpg的帮助文档 ?mpg # help(mpg) ``` -- 1. `displ`: a car's engine size, in litres. 2. `hwy`: a car's fuel efficiency on the highway, in miles per gallon (mpg). 3. `class`: "type" of car ... --- layout: true ### .bold[2.2 将数据.red[映射为几何对象的美学属性]] --- count: false ```r ggplot() ``` <img src="L02_Visualization_files/figure-html/mapping1-1-1.png" width="60%" style="display: block; margin: auto;" /> --- count: false ```r ggplot(data = mpg) # 数据集 ``` <img src="L02_Visualization_files/figure-html/mapping1-2-1.png" width="60%" style="display: block; margin: auto;" /> --- count: false ```r ggplot(data = mpg, # 数据集 mapping = aes(x = displ, y = hwy)) # 映射:变量 -> x坐标和y坐标 ``` <img src="L02_Visualization_files/figure-html/mapping1-3-1.png" width="60%" style="display: block; margin: auto;" /> --- count: false ```r ggplot(data = mpg, # 数据集 mapping = aes(x = displ, y = hwy)) + # 映射:变量 -> x坐标和y坐标 geom_point() # 几何对象 ``` <img src="L02_Visualization_files/figure-html/mapping1-4-1.png" width="60%" style="display: block; margin: auto;" /> --- ```r g_mpg <- ggplot(data = mpg, # 数据集 mapping = aes(x = displ, y = hwy)) + # 映射:变量 -> x坐标和y坐标 geom_point() # 几何对象 ``` -- .pull-left[ ```r print(g_mpg) ``` <img src="L02_Visualization_files/figure-html/mapping1-6-1.png" width="100%" style="display: block; margin: auto;" /> ] -- .pull-right[ ```r names(g_mpg) ``` ``` #> [1] "data" "layers" #> [3] "scales" "mapping" #> [5] "theme" "coordinates" #> [7] "facet" "plot_env" #> [9] "labels" ``` ```r str(g_mpg) # View(g_mpg) ``` ``` #> List of 9 #> $ data : tibble [234 × 11] (S3: tbl_df/tbl/data.frame) #> ..$ manufacturer: chr [1:234] "audi" "audi" "audi" "audi" ... #> ..$ model : chr [1:234] "a4" "a4" "a4" "a4" ... #> ..$ displ : num [1:234] 1.8 1.8 2 2 2.8 2.8 3.1 1.8 1.8 2 ... #> ..$ year : int [1:234] 1999 1999 2008 2008 1999 1999 2008 1999 1999 2008 ... #> ..$ cyl : int [1:234] 4 4 4 4 6 6 6 4 4 4 ... #> ..$ trans : chr [1:234] "auto(l5)" "manual(m5)" "manual(m6)" "auto(av)" ... #> ..$ drv : chr [1:234] "f" "f" "f" "f" ... #> ..$ cty : int [1:234] 18 21 20 21 16 18 18 18 16 20 ... #> ..$ hwy : int [1:234] 29 29 31 30 26 26 27 26 25 28 ... #> ..$ fl : chr [1:234] "p" "p" "p" "p" ... #> ..$ class : chr [1:234] "compact" "compact" "compact" "compact" ... #> $ layers :List of 1 #> ..$ :Classes 'LayerInstance', 'Layer', 'ggproto', 'gg' <ggproto object: Class LayerInstance, Layer, gg> #> aes_params: list #> compute_aesthetics: function #> compute_geom_1: function #> compute_geom_2: function #> compute_position: function #> compute_statistic: function #> computed_geom_params: list #> computed_mapping: uneval #> computed_stat_params: list #> constructor: call #> data: waiver #> draw_geom: function #> finish_statistics: function #> geom: <ggproto object: Class GeomPoint, Geom, gg> #> aesthetics: function #> default_aes: uneval #> draw_group: function #> draw_key: function #> draw_layer: function #> draw_panel: function #> extra_params: na.rm #> handle_na: function #> non_missing_aes: size shape colour #> optional_aes: #> parameters: function #> rename_size: FALSE #> required_aes: x y #> setup_data: function #> setup_params: function #> use_defaults: function #> super: <ggproto object: Class Geom, gg> #> geom_params: list #> inherit.aes: TRUE #> layer_data: function #> map_statistic: function #> mapping: NULL #> position: <ggproto object: Class PositionIdentity, Position, gg> #> compute_layer: function #> compute_panel: function #> required_aes: #> setup_data: function #> setup_params: function #> super: <ggproto object: Class Position, gg> #> print: function #> setup_layer: function #> show.legend: NA #> stat: <ggproto object: Class StatIdentity, Stat, gg> #> aesthetics: function #> compute_group: function #> compute_layer: function #> compute_panel: function #> default_aes: uneval #> dropped_aes: #> extra_params: na.rm #> finish_layer: function #> non_missing_aes: #> optional_aes: #> parameters: function #> required_aes: #> retransform: TRUE #> setup_data: function #> setup_params: function #> super: <ggproto object: Class Stat, gg> #> stat_params: list #> super: <ggproto object: Class Layer, gg> #> $ scales :Classes 'ScalesList', 'ggproto', 'gg' <ggproto object: Class ScalesList, gg> #> add: function #> clone: function #> find: function #> get_scales: function #> has_scale: function #> input: function #> n: function #> non_position_scales: function #> scales: list #> super: <ggproto object: Class ScalesList, gg> #> $ mapping :List of 2 #> ..$ x: language ~displ #> .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> #> ..$ y: language ~hwy #> .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> #> ..- attr(*, "class")= chr "uneval" #> $ theme : list() #> $ coordinates:Classes 'CoordCartesian', 'Coord', 'ggproto', 'gg' <ggproto object: Class CoordCartesian, Coord, gg> #> aspect: function #> backtransform_range: function #> clip: on #> default: TRUE #> distance: function #> expand: TRUE #> is_free: function #> is_linear: function #> labels: function #> limits: list #> modify_scales: function #> range: function #> render_axis_h: function #> render_axis_v: function #> render_bg: function #> render_fg: function #> setup_data: function #> setup_layout: function #> setup_panel_guides: function #> setup_panel_params: function #> setup_params: function #> train_panel_guides: function #> transform: function #> super: <ggproto object: Class CoordCartesian, Coord, gg> #> $ facet :Classes 'FacetNull', 'Facet', 'ggproto', 'gg' <ggproto object: Class FacetNull, Facet, gg> #> compute_layout: function #> draw_back: function #> draw_front: function #> draw_labels: function #> draw_panels: function #> finish_data: function #> init_scales: function #> map_data: function #> params: list #> setup_data: function #> setup_params: function #> shrink: TRUE #> train_scales: function #> vars: function #> super: <ggproto object: Class FacetNull, Facet, gg> #> $ plot_env :<environment: R_GlobalEnv> #> $ labels :List of 2 #> ..$ x: chr "displ" #> ..$ y: chr "hwy" #> - attr(*, "class")= chr [1:2] "gg" "ggplot" ``` ] --- ```r ggplot(data = mpg) + geom_point( * mapping = aes(x = displ, y = hwy, colour = class) # 3个映射 ) ``` <img src="L02_Visualization_files/figure-html/mapping2-1.png" width="60%" style="display: block; margin: auto;" /> --- ```r ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, shape = class)) ``` ``` #> Warning: The shape palette can deal with a maximum of 6 discrete values because more than #> 6 becomes difficult to discriminate; you have 7. Consider specifying shapes #> manually if you must have them. ``` ``` #> Warning: Removed 62 rows containing missing values (`geom_point()`). ``` <img src="L02_Visualization_files/figure-html/mapping3-1.png" width="60%" style="display: block; margin: auto;" /> --- .font120[ - R内置有25个形状(shape),在`ggplot2`中可用名字或数字进行设定 ] .pull-left[ <img src="L02_Visualization_files/figure-html/shapes-name-1.png" width="95%" style="display: block; margin: auto;" /> ] -- .pull-right[ <img src="L02_Visualization_files/figure-html/shapes-id-1.png" width="95%" style="display: block; margin: auto;" /> ] -- .font120[ - 设定图形属性相关的说明文档 .content-box-yellow.font80[`vignette("ggplot2-specs")`] ] --- ```r ggplot(data = mpg) + geom_point( mapping = aes(x = displ, y = hwy), * shape = "triangle", size = 3, colour = "red", alpha = 0.3 # 变量无关(“大家都一样”,即非映射)的几何对象图形属性应在aes()外进行设定 ) ``` <img src="L02_Visualization_files/figure-html/mapping4-1.png" width="55%" style="display: block; margin: auto;" /> --- ```r # layered! ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy)) + * geom_smooth(mapping = aes(x = displ, y = hwy)) # layered! ``` <img src="L02_Visualization_files/figure-html/mapping5-1.png" width="58%" style="display: block; margin: auto;" /> --- ```r ggplot( data = mpg, * mapping = aes(x = displ, y = hwy) # 共用映射,提前至ggplot()中 ) + geom_point() + geom_smooth() ``` <img src="L02_Visualization_files/figure-html/mapping6-1.png" width="56%" style="display: block; margin: auto;" /> --- ```r *ggplot(mpg, aes(displ, hwy)) + # 省略常用参数名 * geom_point(aes(colour = class)) + # 图层自用映射 * geom_smooth(data = filter(mpg, class == "pickup")) # 不同的数据集 ``` <img src="L02_Visualization_files/figure-html/mapping7-1.png" width="65%" style="display: block; margin: auto;" /> --- layout: false class: hide_logo ## 🙋♂️ Your Turn! <style type="text/css"> #special_timer.running { background-color: black; background-image: url(imgs/bg-stars.gif); } #special_timer.finished { background-color: black; background-image: url(imgs/bg-sqfw.gif); background-size: cover; } #special_timer.running .countdown-digits { color: #fdf6e3; } #special_timer.finished .countdown-digits { color: #fdf6e3; } </style>
−
+
05
:
00
<br> .pull-left[ .font120[在 RStudio控制台 中输入以下代码(高亮处填补恰当内容——记得善用.kbd[`F1`] ),从而得到右边所示的图形:] <code class ='r hljs remark-code'>library(ggplot2)<br><br>ggplot(economics) + <br> geom_hline(<br> <span style="background-color:#ffff7f"> </span> = 3.5, <br> <span style="background-color:#ffff7f"> </span> = 'white', <br> <span style="background-color:#ffff7f"> </span> = 2<br> ) +<br> geom<span style="background-color:#ffff7f"> </span>(<br> aes(x = <span style="background-color:#ffff7f"> </span>, <br> y = <span style="background-color:#ffff7f"> </span>)<br> )</code> <img src="L02_Visualization_files/figure-html/yt-0-flaired-1.png" width="0.1" /> ] .pull-right[ <br><br> <img src="L02_Visualization_files/figure-html/yt-2-1.png" width="100%" style="display: block; margin: auto;" /> ] --- layout: true ### .bold[2.3 .red[统计变换]、位置调整、坐标、分面] --- ```r ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut)) ``` -- <img src="L02_Visualization_files/figure-html/stat2-1.png" width="65%" style="display: block; margin: auto;" /> .red.font110[Where comes the "count" in y-axis? 😅] --- <img src="imgs/visualization-stat-bar.png" width="100%" style="display: block; margin: auto;" /> -- .font110[下面的代码会得到和使用 `geom_bar()` 相同的结果] ```r ggplot(data = diamonds) + * stat_count(mapping = aes(x = cut)) ``` --- ```r ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, y = after_stat(prop), # ?aes_eval group = 1)) # ?aes_group_order ``` <img src="L02_Visualization_files/figure-html/stat3-2-1.png" width="60%" style="display: block; margin: auto;" /> --- ```r ggplot(data = diamonds %>% group_by(cut) %>% count()) + # what's this?! geom_bar( mapping = aes(x = cut, y = n), * stat = "identity" ) ``` <img src="L02_Visualization_files/figure-html/stat4-1.png" width="58%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.3 统计变换、.red[位置调整]、坐标、分面] --- ```r ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity)) # geom_bar()默认的position = "stack" ``` <img src="L02_Visualization_files/figure-html/pos1-1.png" width="65%" style="display: block; margin: auto;" /> --- ```r ggplot(data = diamonds) + geom_bar( mapping = aes(x = cut, fill = clarity), * position = "dodge" # position = position_dodge(width = 0.9) ) ``` <img src="L02_Visualization_files/figure-html/pos2-1.png" width="58%" style="display: block; margin: auto;" /> --- ```r ggplot(data = mpg) + geom_point( mapping = aes(x = displ, y = hwy), * position = "jitter" # same as `ggplot() + geom_jitter()` ) ``` <img src="L02_Visualization_files/figure-html/pos3-1.png" width="58%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.3 统计变换、位置调整、.red[坐标]、分面] --- ```r ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + geom_boxplot() + * coord_flip() # ggplot2 3.3.0后直接调换x,y参数即可 ``` <img src="L02_Visualization_files/figure-html/coord1-1.png" width="65%" style="display: block; margin: auto;" /> --- ```r bar <- ggplot(data = diamonds) + # 将图形对象存为变量bar,可在Environment标签页中检查其内容 geom_bar( mapping = aes(x = cut, fill = cut), show.legend = FALSE, width = 1 ) + theme(aspect.ratio = 1) + labs(x = NULL, y = NULL) *bar + coord_polar() ``` <img src="L02_Visualization_files/figure-html/coord2-1.png" width="35%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.3 统计变换、位置调整、坐标、.red[分面]] --- ```r ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point(data = mutate(mpg, class = NULL), colour = "grey") + geom_point() + * facet_wrap(vars(class), nrow = 2) # facet_wrap(~ class, nrow = 2) ``` <img src="L02_Visualization_files/figure-html/facet1-1.png" width="65%" style="display: block; margin: auto;" /> --- ```r ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point(data = transform(mpg, cyl = NULL), colour = "grey") + geom_point() + * facet_grid(rows = vars(drv), cols = vars(cyl)) # facet_grid(drv ~ cyl) ``` <img src="L02_Visualization_files/figure-html/facet2-1.png" width="65%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.4 .red[标签]、标注、标度、主题等] --- ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + geom_smooth(se = FALSE) + * labs( # 标题、小标题等 * title = "Fuel efficiency", * subtitle = "... generally decreases with engine size", * caption = "Data from fueleconomy.gov" * ) ``` <img src="L02_Visualization_files/figure-html/labs1-1.png" width="50%" style="display: block; margin: auto;" /> --- ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + geom_smooth(se = FALSE) + * labs( # 图形属性 = 标签 * x = "Engine displacement (L)", * y = "Highway fuel economy (mpg)", * colour = "Car type" * ) ``` <img src="L02_Visualization_files/figure-html/labs2-1.png" width="50%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.4 标签、.red[标注]、标度、主题等] --- ```r # 生成辅助数据集 best <- mpg %>% group_by(class) %>% filter(row_number(desc(hwy)) == 1) ``` -- .pull-left[ ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + * geom_text( aes(label = model), data = best ) ``` <img src="L02_Visualization_files/figure-html/label1-1.png" width="85%" style="display: block; margin: auto;" /> ] -- .pull-right[ ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + * geom_label( aes(label = model), data = best, nudge_y = 2, alpha = 0.5 ) ``` <img src="L02_Visualization_files/figure-html/label2-1.png" width="85%" style="display: block; margin: auto;" /> ] --- ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + * geom_point(size = 3, shape = 1, data = best) + * ggrepel::geom_label_repel(aes(label = model), data = best) # install ggrepel ``` <img src="L02_Visualization_files/figure-html/label3-1.png" width="65%" style="display: block; margin: auto;" /> --- .pull-left.code75[ ```r *library(ggtext) # install it! # 辅助数据 beetle <- mpg %>% filter(model == "new beetle") %>% filter(hwy == max(hwy)) %>% mutate(model = "<img src='imgs/beetle.png' width='25'/>") ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + * geom_richtext( data = beetle, aes(label = model), fill = NA, colour = NA, hjust = 0, vjust = 0.5 ) + labs( title = "<b>Fuel efficiency</b><br> <span style='color:red;font-size:12pt'> ... generally **_decreases_** with engine size</span>" ) -> p ``` ] .pull-right.code75[ ```r p + theme( plot.title.position = "plot", * plot.title = element_textbox_simple( size = 15, lineheight = 1.2, padding = margin(5.5, 5.5, 5.5, 5.5), margin = margin(0, 0, 5.5, 0), linetype = 1, r = grid::unit(8, "pt"), fill = "#F0F7FF" )) ``` <img src="L02_Visualization_files/figure-html/label4-2-1.png" width="100%" style="display: block; margin: auto;" /> ] --- layout: true ### .bold[2.4 标签、标注、.red[标度]、主题等] --- ```r ggplot(diamonds, aes(carat, price)) + geom_bin2d() + * scale_x_log10() + * scale_y_log10() ``` <img src="L02_Visualization_files/figure-html/scale1-1.png" width="65%" style="display: block; margin: auto;" /> --- ```r ggplot(mpg, aes(displ, hwy)) + geom_point() + * scale_y_continuous( name = "Highway fuel economy (mpg)", breaks = seq(0, 50, by = 10), limits = c(0, 100), expand = expansion(mult = 0.09, add = 1) ) ``` <img src="L02_Visualization_files/figure-html/scale2-1.png" width="55%" style="display: block; margin: auto;" /> --- ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = drv, shape = drv)) + * scale_colour_brewer(palette = "Set1") # RColorBrewer::display.brewer.all() ``` <img src="L02_Visualization_files/figure-html/scale3-1.png" width="65%" style="display: block; margin: auto;" /> --- ```r ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + * theme(legend.position = "bottom") + guides( * colour = guide_legend(nrow = 1, override.aes = list(size = 3)) ) ``` <img src="L02_Visualization_files/figure-html/scale4-1.png" width="55%" style="display: block; margin: auto;" /> --- layout: true ### .bold[2.4 标签、标注、标度、.red[主题]等] --- .pull-left[ ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + geom_smooth(se = FALSE) + * theme_minimal() ``` <img src="L02_Visualization_files/figure-html/theme1-1.png" width="100%" style="display: block; margin: auto;" /> ] -- .pull-right[ ```r ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = class)) + geom_smooth(se = FALSE) + * ggthemes::theme_stata() # install it! ``` <img src="L02_Visualization_files/figure-html/theme2-1.png" width="100%" style="display: block; margin: auto;" /> ] --- .code80[ ```r theme(line, rect, text, title, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, axis.text.y.right, axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, legend.background, legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y, legend.key, legend.key.size, legend.key.height, legend.key.width, legend.text, legend.text.align, legend.title, legend.title.align, legend.position, legend.direction, legend.justification, legend.box, legend.box.just, legend.box.margin, legend.box.background, legend.box.spacing, panel.background, panel.border, panel.spacing, panel.spacing.x, panel.spacing.y, panel.grid, panel.grid.major, panel.grid.minor, panel.grid.major.x, panel.grid.major.y, panel.grid.minor.x, panel.grid.minor.y, panel.ontop, plot.background, plot.title, plot.title.position, plot.subtitle, plot.caption, plot.caption.position, plot.tag, plot.tag.position, plot.margin, strip.background, strip.background.x, strip.background.y, strip.clip, strip.placement, strip.text, strip.text.x, strip.text.x.bottom, strip.text.x.top, strip.text.y, strip.text.y.left, strip.text.y.right, strip.switch.pad.grid, strip.switch.pad.wrap, ..., complete = FALSE, validate = TRUE) ``` ] --- <iframe src="https://rstudio.github.io/thematic/" width="100%" height="550px" data-external="1"></iframe> --- layout: false class: hide_logo ## 🙋♂️ Your Turn!
−
+
10
:
00
<br> .pull-left[ .font120[在 RStudio控制台 中输入恰当的代码从而得到右边所示的图形:] ```r # install.packages("palmerpenguins") # install.packages("ggthemes") library(ggplot2) library(ggthemes) palmerpenguins::penguins %>% ... ``` ] .pull-right[ <br><br> <img src="L02_Visualization_files/figure-html/pg-2-1.png" width="100%" style="display: block; margin: auto;" /> ] --- layout: false class: inverse, center, middle # 3. `ggplot2` extensions and ... --- class: hide_logo background-image: url(imgs/logo-esquisse.png) background-size: 5% background-position: 5% 3% ###   `esquisse`<sup>.font60[v1.1.2]</sup> .pull-left.font110[ > This `esquisse` addin allows you to interactively > explore your data by visualizing it with the `ggplot2` > package. It allows you to draw bar plots, curves, > scatter plots, histograms, boxplot and sf objects, > then export the graph or retrieve the code to reproduce > the graph. <br> ```r # install.packages("esquisse") # RStudio Addins -> 'ggplot2' builder esquisse::esquisser() ``` ] -- .pull-right[ <br> <img src="imgs/esquisse.gif" width="100%" style="display: block; margin: auto auto auto 0;" /> ] --- class: hide_logo background-image: url(imgs/logo-patchwork.png) background-size: 5% background-position: 5% 3% ###   `patchwork`<sup>.font60[v1.1.3]</sup> .pull-left.font110[ > `patchwork` expands the API to allow > for arbitrarily complex composition of > plots by, among others, providing > mathematical operators for combining > multiple plots. ```r # install.packages("patchwork") library(patchwork) p <- ggplot(mtcars) p1 <- p + geom_point(aes(mpg, disp)) p2 <- p + geom_boxplot( aes(gear, disp, group = gear)) p3 <- p + geom_smooth(aes(disp, qsec)) p4 <- p + geom_bar(aes(carb)) ``` ] -- .pull-right[ ```r p1 + plot_spacer() + { p2 + p3 + plot_layout(ncol = 1) } + plot_layout(nrow = 1, widths = c(1, 0.25, 1)) - p4 + plot_layout(ncol = 1) + plot_annotation(title = "Fancy plot!", tag_levels = "A") ``` <img src="L02_Visualization_files/figure-html/patchwork-1.png" width="95%" style="display: block; margin: auto;" /> ] --- class: hide_logo background-image: url(imgs/logo-gganimate.png) background-size: 5% background-position: 5% 3% ###   `gganimate`<sup>.font60[v1.0.8]</sup> .pull-left[ <br> ```r # install.packages("gganimate") # install.packages("gifski") # install.packages("gapminder") library(gganimate) library(gapminder) p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) + geom_point(alpha = 0.7, show.legend = FALSE) + scale_colour_manual( values = country_colors ) + scale_size(range = c(2, 12)) + scale_x_log10() + facet_wrap(vars(continent)) ``` ] -- .pull-right[ ```r # Here comes the gganimate specific bits *p + labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + * transition_time(year) + * ease_aes('linear') ``` <img src="L02_Visualization_files/figure-html/gganimate-1.gif" width="100%" style="display: block; margin: auto;" /> <!-- ![](L02_Visualization_files/figure-html/gganimate-1.gif) --> ] --- class: hide_logo background-image: url(imgs/logo-plotly.png) background-size: 5% background-position: 5% 3% ###   `plotly`<sup>.font60[v4.10.2]</sup> .pull-left.font110[ > Create interactive web graphics from `ggplot2` graphs > and/or a custom interface to the 'plotly.js' > inspired by the _grammar of graphics_. ```r # install.packages("plotly") *library(plotly) p <- gapminder %>% filter(year == 2007) %>% ggplot(aes(gdpPercap, lifeExp, size = pop, color = continent)) + geom_point() + scale_x_log10() + theme_bw() *ggplotly(p) ``` ] -- .pull-right[ <br>
] --- class: hide_logo background-image: url(imgs/logo-plotnine.webp) background-size: 5% background-position: 5% 3% ###   `plotnine`: A Grammar of Graphics for Python <iframe src="https://plotnine.readthedocs.io/" width="100%" height="540px" data-external="1"></iframe> --- class: inverse, center, middle # 课后复习与作业 --- class: middle .font130[ 🕐 根据课程讲义的打印稿,在 📑 _R Script_ 中键入并完成全部代码的运行 🕑 请复习 / 进一步学习 📖 .bold[[{{_R for Data Science, 2e_}}](https://r4ds.hadley.nz/)] <sup>*</sup> 一书关于数据可视化的第2章(Data visualization)、第10章(Layers)和__第12章(Communication)__以及关于工作流的第3、5、7、9章) 🕒 下载(打印)📰 .bold[[{{ggplot2-cheatsheet}}](docs/ggplot2-cheatsheet.pdf)] 并浏览之 🕓 登录浏览 🖼 .bold[[{{The R Graph Gallery}}](https://www.r-graph-gallery.com/index.html)] 🕔 登录浏览 📦 .bold[[{{ggplot2 extentions}}](https://exts.ggplot2.tidyverse.org/gallery/)],进一步了解 `ggplot2` 包的“生态圈” 🕕 _**进阶内容**_:R 对中文字体的支持不够理想,可参考 📝 .bold[[{{_RJournal_的文章}}](https://journal.r-project.org/archive/2015-1/qiu.pdf)]以及帖子 .bold[[{{showtext}}](https://cosx.org/2014/01/showtext-interesting-fonts-and-graphs)] 中提到的解决方案和有趣示例 <br> ] .footnote.red[ \* 若英文看起来实在吃力 😵, 这本书的第一版有中文翻译版,请同学们自行学习对应章节。我个人建议同学们(等网上商城打折时)购买实体书,放在案头作学习参考。] --- class: middle .font120[ 🕐 根据 L2 课程讲义的打印稿,在 📑 _R Script_ 中键入并完成全部代码的运行 ] -- - .bold[打开新的 R script 文件] - .kbd[`Ctrl+Shift+N`] 打开 -> .kbd[`Ctrl+S`] 存盘为“_L02_coding_practice.R_” - 注:文件保存路径和文件名最好为英文,中间不要有空格 -- - .bold[输入与运行代码] - 长代码手动断行,最好不要超过80个字符 - 灵活使用快捷键,如 .kbd[`F1`](帮助)、.kbd[`Tab`](代码提示与自动补全)、.kbd[`Ctrl+A`](选中全部代码) -> .kbd[`Ctrl+Shift+A`](代码重新格式化)等 - .kbd[`Ctrl+Enter`] 运行光标所在行或选中代码(.kbd[`Ctrl+Alt+R`] 运行全部代码,.kbd[`Ctrl+Shift+P`] 重新运行代码,.kbd[`Ctrl+Alt+P`] 运行光标前的代码) -- - .bold[注释] - 以 # 作为注释开始标记,如说明性文字、区分不同代码块(.kbd[`Ctrl+Shift+R`]) - 最后加入一段注释说明,简单说说使用 ggplot2包 的体会 -- - .bold[提交代码] - 可结队编写代码,共同署名,分别提交,**但注意控制雷同比例** - 2023年9月28日22:00前通过 [{{坚果云链接}}](https://send2me.cn/mhGkgKHx/S_mh3x3-oCKUzg) 直接提交代码文档 --- class: center middle background-image: url(imgs/xaringan.png) background-size: 12% background-position: 50% 40% <br><br><br><br><br><br><br> <hr color='#f00' size='2px' width='80%'> <br> .Large.red[_**本网页版讲义的制作由 R 包 [{{`xaringan`}}](https://github.com/yihui/xaringan) 赋能!**_]