class: center, middle, inverse, title-slide # ggplot Detailed Features ## for OECD Charte Graphique ### 2017/06/29 --- class: inverse2, center, middle # OECDPlotR ![](under_construction.gif) --- ## OECDPlotR: Column Chart ```r ggplot(data=dat1, aes(x=time, y=scrap, fill=dat1$region)) + geom_barOECD(scaled=TRUE, # Used to pass on default to OECDggplotscale() stat="identity", position=position_dodge()) + OECDggplotscale(name="Country",scaleType = "fill") + # pecify color of scaling xlab("Year") + ylab("Scrap") + ggtitle("China Plastic Scrap") + OECDtheme() ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-1-1.svg)<!-- --> --- ```r ggplot(data=dat1, aes(x=time, y=scrap, fill=dat1$region)) + geom_barOECD(scaled=TRUE, stat="identity", position=position_dodge()) + coord_flip() + OECDggplotscale(name="Country",scaleType = "fill") + xlab("Year") + ylab("Scrap") + ggtitle("China Plastic Scrap") + OECDtheme() ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-2-1.svg)<!-- --> --- ## OECDPlotR: Stacked Column ```r ggplot(data=dat1, aes(x=time, y=scrap, fill=dat1$region)) + geom_barOECD(scaled=TRUE, stat="identity") + OECDggplotscale(name="Country",scaleType = "fill") + xlab("Year") + ylab("Scrap")+ OECDtheme() ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-3-1.svg)<!-- --> --- ## OECDPlotR: STI-OLIS Theme ```r ggplot(data=dat1, aes(x=time, y=scrap, fill=dat1$region)) + geom_barOECD(scaled=TRUE, stat="identity") + OECDggplotscale(name="Country",scaleType = "fill") + xlab("Year") + ylab("Scrap") + ggtitle("China Plastic Scrap") + OECDtheme() ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-4-1.svg)<!-- --> --- ## OECDPlotR: Other Features ```r ggplot(mpg, aes(class)) + geom_barOECD(aes(fill = drv), position = position_stack(reverse = TRUE),scaled = TRUE) + OECDggplotscale(scaleType="fill")+ OECDtheme() ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-10-1.svg)<!-- --> --- ## OECDPlotR: Other Features ```r ggplot(mpg, aes(class)) + geom_barOECD(aes(fill = drv), position = position_stack(reverse = TRUE),scaled = TRUE) + OECDggplotscale(scaleType="fill") + OECDtheme(inbox = TRUE) ``` ![](10-ggplot-detailed-features/fig-html/oecdplotr-bar-11-1.svg)<!-- --> --- class: inverse, center, middle # theming http://ggplot2.tidyverse.org/reference/theme.html --- ## Grobs: Legend Width ```r gp <- ggplot2::ggplotGrob(p) leg <- gtable::gtable_filter(gp, "guide-box") panel <- gtable::gtable_filter(gp, "panel") leg[[1]][[1]]$widths[[elem]] = panel$grobs[[1]]$children[[1]]$children[[1]]$width - sum(leg[[1]][[1]]$widths) + leg[[1]][[1]]$widths[[elem]] gp.new = gtable::gtable_add_grob(gp, leg, t = 4, l = 4) ``` ![](10-ggplot-detailed-features/fig-html/legend-width-eval-1.svg)<!-- --> --- ## Legend Guides It is possible to specify the `legend.key` height and width separately for each guide (colour, linetype etc.), see [guide_legend.html](http://ggplot2.tidyverse.org/reference/guide_legend.html) ```r p2 <- p1 + guides(fill = guide_legend(keywidth = unit(10, "mm"), keyheight = unit(10, "mm"), title = "", override.aes = list(color = "black")), linetype = guide_legend(keywidth = unit(20, "mm"), title = "")) gp2 <- absLegend(p2); grid.newpage(); grid.draw(gp2) ``` ![](10-ggplot-detailed-features/fig-html/key-size-1.svg)<!-- --> --- ## Y-Axis Position The y-axis title position can be modified in the theme using the parameters of `element_text`, see [theme elements](http://ggplot2.tidyverse.org/reference/element.html) ```r p2 <- p1 + scale_y_continuous(name = "%") + theme(axis.title.y = element_text(vjust = 1.08, angle = 0, margin = margin(r = -10, unit = "pt"))) gp2 <- absLegend(p2); grid.newpage(); grid.draw(gp2) ``` ![](10-ggplot-detailed-features/fig-html/axis-title-position-1.svg)<!-- --> --- ## Secondary Y-Axis The `sec.axis` parameter of `scale_y_continuous` can define a transformed version of the primary y-axis, see [sec_axis()](http://ggplot2.tidyverse.org/reference/sec_axis.html). Prior to plotting, series with different units need to be scaled to the same unit manually. ```r ggplot(mtcars, aes(cyl, mpg)) + geom_point() ``` ![](10-ggplot-detailed-features/fig-html/sec-axis-1.svg)<!-- --> --- We may want to display the levels of `mpg` and `hp` on the same plot
```r mtcars %>% select(mpg, hp) %>% mutate(hp_scaled = hp / 10) %>% summary() ``` ``` ## mpg hp hp_scaled ## Min. :10.40 Min. : 52.0 Min. : 5.20 ## 1st Qu.:15.43 1st Qu.: 96.5 1st Qu.: 9.65 ## Median :19.20 Median :123.0 Median :12.30 ## Mean :20.09 Mean :146.7 Mean :14.67 ## 3rd Qu.:22.80 3rd Qu.:180.0 3rd Qu.:18.00 ## Max. :33.90 Max. :335.0 Max. :33.50 ``` --- Plot on separate axes, manual axis title and legend labels ```r scalefactor <- 10^1; p1 <- mtcars %>% mutate(hp_scaled = hp / scalefactor) %>% select(cyl, mpg, hp_scaled) %>% gather(key = variable, value = value, -cyl) %>% ggplot(aes(x=cyl, y = value, color = variable)) + geom_point() + scale_y_continuous(name = "mpg", sec.axis = sec_axis(name="hp", ~.*scalefactor)) + scale_color_discrete(labels = c("hp", "mpg")) + guides(color = guide_legend(title = NULL)) + theme(legend.position = "top", legend.background = element_rect(fill = FALSE, color = FALSE), legend.margin = margin(0.5, 0, 0.5, 0, unit = "mm"), # trbl legend.key = element_rect(color = FALSE, fill = FALSE)) grid.newpage(); p1 %>% absLegend() %>% grid.draw() ``` ![](10-ggplot-detailed-features/fig-html/rescale-mtcars-1.svg)<!-- --> --- class: inverse, center, middle # aesthetics --- ## data labels The `geom_text` layer accepts parameters for `element_text`, for details see [geom_text](http://ggplot2.tidyverse.org/reference/geom_text.html). The fonts must be installed on your computer. ```r ## labelpos = 100 - (cumsum(pct) - pct / 2) p + geom_text(aes(y = labelpos, label = paste0(as.character(pct), "%")), family = "serif", size = 6, color = "red") + coord_polar(theta = "y") ``` ![](10-ggplot-detailed-features/fig-html/pie-label-1.svg)<!-- --> --- ## High Low Plot Analogue to colors, linetypes and shapes can be mapped to variables, see [Shapes and line types](http://www.cookbook-r.com/Graphs/Shapes_and_line_types/) ```r p_hl <- ggplot(data = df_hl, aes(x = date, y = value, color = label, fill = label)) + geom_point(aes(shape = label), size = 2) + scale_shape_manual(values = c(17, 23, 15)) themeHighLow(p = p_hl, col = c("black", "#4f81bd", "black")) ``` ![](10-ggplot-detailed-features/fig-html/high-low-plot-base-1.svg)<!-- --> --- ## High Low Plot with Lines `geom_segment` allows drawing arbitrary lines, see [Line segments and curves](http://ggplot2.tidyverse.org/reference/geom_segment.html) ```r df_hl2 <- df_hl %>% group_by(date) %>% mutate(min=min(value), max=(max(value))) %>% ungroup() p_hl2 <- ggplot(data = df_hl2, aes( x = date, y = value, color = label, fill = label )) + geom_point( aes( shape = label ), size = 2) + geom_segment( aes( xend = date, y = min, yend = max ), size = 0.05) + scale_shape_manual(values = c(17, 23, 15)); themeHighLow(p = p_hl2) ``` ![](10-ggplot-detailed-features/fig-html/high-low-plot-line-1.svg)<!-- --> --- class: inverse, center, middle # extensions --- ## Radar Plot Data extracted from http://stats.oecd.org/Index.aspx?DataSetCode=BLI ``` mutate_at(vars(-LOCATION), funs(scales::rescale)) ``` ``` ## 'data.frame': 2 obs. of 25 variables: ## $ group : Factor w/ 39 levels "AUS","AUT","BEL",..: 14 21 ## $ Air pollution : num 0.348 0.522 ## $ Dwellings without basic facilities : num 0.0244 0.039 ## $ Educational attainment : num 0.672 0.469 ## $ Employees working very long hours : num 0.1573 0.0635 ## $ Employment rate : num 0.62 0.34 ## $ Feeling safe walking alone at night : num 0.636 0.437 ## $ Homicide rate : num 0.08 0.08 ## $ Household net adjusted disposable income : num 0.65 0.503 ## $ Household net financial wealth : num 0.314 0.333 ## $ Housing expenditure : num 0.667 0.867 ## $ Labour market insecurity : num 0.222 0.371 ## $ Life expectancy : num 0.964 0.95 ## $ Life satisfaction : num 0.517 0.345 ## $ Long-term unemployment rate : num 0.176 0.386 ## $ Personal earnings : num 0.622 0.533 ## $ Quality of support network : num 0.5 0.5 ## $ Rooms per person : num 0.611 0.389 ## $ Self-reported health : num 0.552 0.517 ## $ Stakeholder engagement for developing regulations: num 0.481 0.259 ## $ Student skills : num 0.734 0.64 ## $ Time devoted to leisure and personal care : num 1 0.592 ## $ Voter turnout : num 0.729 0.562 ## $ Water quality : num 0.755 0.367 ## $ Years in education : num 0.356 0.441 ``` --- ## Radar Plot The existing ggplot2 extension [ggradar](http://www.ggplot2-exts.org/ggradar.html) can be modified. Alternatively, the [plotrix package](https://cran.r-project.org/web/packages/plotrix/index.html) can be tested. More examples can be found [here](http://boot.rdata.work/contrib/radar-example/) ```r p_radar <- ggradar(bli_radar, font.radar = "sans", grid.label.size = 4, axis.label.size = 4, group.point.size = 1, group.line.width = 1, plot.extent.x.sf = 1.8) + scale_color_manual(values = c("#8cc841", "#da2128")) + theme( legend.position = c(0.05, 0.95), legend.justification = "left", legend.direction = "horizontal", legend.text = element_text(size = 8), legend.background = element_rect(fill = NULL) ) ``` --- ## Radar Plot ![](10-ggplot-detailed-features/fig-html/radar-chart-2-1.svg)<!-- --> --- class: inverse, center, middle # hrbrthemes https://github.com/hrbrmstr/hrbrthemes --- ```r ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + geom_area() + scale_fill_ipsum() + scale_x_continuous(expand=c(0,0)) + scale_y_comma() + labs(title="Age distribution of population in the U.S., 1900-2002", subtitle="Example data from the R Graphics Cookbook", caption="Source: R Graphics Cookbook") + theme_ipsum_rc(grid="XY") + theme(legend.position="right") + theme(axis.text.x=element_text(hjust=c(0, 0.5, 0.5, 0.5, 1))) ``` ![](10-ggplot-detailed-features/fig-html/hrbrthemes-example-area-1.svg)<!-- --> --- ``` ## R version 3.4.1 (2017-06-30) ## Platform: x86_64-redhat-linux-gnu (64-bit) ## Running under: Fedora 26 (Workstation Edition) ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib64/R/lib/libRblas.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 ## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C ## [9] LC_ADDRESS=C LC_TELEPHONE=C ## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C ## ## attached base packages: ## [1] grid stats graphics grDevices utils datasets base ## ## other attached packages: ## [1] bindrcpp_0.2 DT_0.2 knitr_1.17 OECDplot_1.5.6 ## [5] gcookbook_1.0 hrbrthemes_0.1.0 scales_0.5.0 ggradar_0.1 ## [9] gtable_0.2.0 tidyr_0.7.0 dplyr_0.7.2 ggplot2_2.2.1 ## [13] rmarkdown_1.6 ## ## loaded via a namespace (and not attached): ## [1] Rcpp_0.12.12 compiler_3.4.1 plyr_1.8.4 bindr_0.1 ## [5] methods_3.4.1 tools_3.4.1 extrafont_0.17 digest_0.6.12 ## [9] evaluate_0.10.1 tibble_1.3.4 pkgconfig_2.0.1 rlang_0.1.2 ## [13] yaml_2.1.14 hunspell_2.5 Rttf2pt1_1.3.4 stringr_1.2.0 ## [17] htmlwidgets_0.9 rprojroot_1.2 glue_1.1.1 R6_2.2.2 ## [21] XML_3.98-1.9 xaringan_0.3 purrr_0.2.3 extrafontdb_1.0 ## [25] magrittr_1.5 backports_1.1.0 htmltools_0.3.6 assertthat_0.2.0 ## [29] colorspace_1.3-2 labeling_0.3 stringi_1.1.5 lazyeval_0.2.0 ## [33] munsell_0.4.3 ```