├── .gitignore ├── LICENSE ├── README.md ├── map_building_1 ├── .gitignore ├── README.md ├── map.R ├── map_building_1.Rproj ├── modis_land_cover.tif └── output │ ├── 01.png │ ├── 02.png │ ├── 03.png │ ├── 04.png │ ├── 05.png │ ├── 07.png │ └── map.gif ├── map_building_2 ├── map.R ├── map_building_2.Rproj └── output │ ├── 01.png │ ├── 02.png │ ├── 03.png │ └── 04.png ├── map_building_3 ├── data │ ├── 00_download_data.R │ └── uv_temp.nc ├── drink_or_rub.png ├── map.R └── mapping_example.Rproj ├── map_building_4 ├── animation.R ├── data │ └── 00_download_data.R ├── map.gif ├── map_building_4.Rproj └── video.mp4 └── map_building_5 ├── data ├── 00_download_data.R └── wind.nc ├── map.png ├── map_building_5.Rproj └── wind_map.R /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .Renviron 4 | .RData 5 | .Ruserdata 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. 438 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://upload.wikimedia.org/wikipedia/commons/1/12/Cc-by-nc-sa_icon.svg) 2 | 3 | # R tutorials in processing and visualization of environmental data 4 | 5 | This is a repository containing all tutorials as highlighted in our [blog](https://bluegreenlabs.org/categories/tutorial/). The code is well annotated but for more context we refer to our blog posts. 6 | 7 | ## How to cite these code snippets in your article 8 | 9 | You can cite this code as "We used processing / vizualization as outlined in Hufkens & Kearsley (2022)". With the following bibliographic reference to include in your reference list: 10 | 11 | > Hufkens, K. & E. Kearsley. BlueGreen Labs (2022). (Version v1.2.0). R tutorials in processing and visualization of environmental data. Zenodo. [http://doi.org/10.5281/zenodo.7004926](http://doi.org/10.5281/zenodo.7004926). 12 | -------------------------------------------------------------------------------- /map_building_1/.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .Renviron 4 | .RData 5 | .Ruserdata 6 | -------------------------------------------------------------------------------- /map_building_1/README.md: -------------------------------------------------------------------------------- 1 | # Map building part 1 2 | 3 | This tutorial shows how you can build a fancy map in ggplot2 and R, layer by layer. To reproduce the process load the R project and read along in the R file. For more details see our blog post. 4 | 5 | ![](output/map.gif) -------------------------------------------------------------------------------- /map_building_1/map.R: -------------------------------------------------------------------------------- 1 | # read libraries 2 | library(tidyverse) 3 | library(rnaturalearth) 4 | library(sf) 5 | library(raster) 6 | library(ggrepel) 7 | library(showtext) 8 | font_add_google( 9 | "Lato", 10 | regular.wt = 300, 11 | bold.wt = 700) 12 | 13 | # grab natural earth polygon data 14 | if(!exists("land")){ 15 | land <- ne_download( 16 | scale = 50, 17 | type = "land", 18 | category = "physical", 19 | returnclass = "sf") 20 | countries <- ne_countries( 21 | returnclass = "sf", 22 | scale = 50) 23 | } 24 | 25 | theme_map <- function(...) { 26 | theme_minimal() + 27 | theme( 28 | text = element_text(family = "Lato", color = "#22211d"), 29 | axis.line = element_blank(), 30 | axis.ticks = element_blank(), 31 | axis.title.x = element_blank(), 32 | axis.title.y = element_blank(), 33 | axis.text = element_blank(), 34 | panel.grid.major = element_blank(), 35 | panel.grid.minor = element_blank(), 36 | plot.background = element_rect(fill = "lightblue", color = NA), 37 | panel.background = element_rect(fill = "lightblue", color = NA), 38 | legend.background = element_rect(fill = "#ffffff", color = NA), 39 | strip.background=element_blank(), 40 | plot.margin = margin(0,0,0,0,"cm"), 41 | panel.border = element_blank(), 42 | ... 43 | ) 44 | } 45 | 46 | # create dataframe with locations 47 | df <- data.frame( 48 | site = c("A", "B"), 49 | lat = c(30, 40), 50 | lon = c(0, 0) 51 | ) 52 | 53 | # read in the land cover data 54 | lc <- raster("modis_land_cover.tif") 55 | 56 | # select only "tree" areas (classes 1 - 9) 57 | # and convert to binary (1 == tree) 58 | lc <- (lc > 0 & lc < 9) 59 | 60 | # reassign the name of the variable "lc" 61 | # see below 62 | names(lc) <- "lc" 63 | 64 | # convert from matrix to long format 65 | # 1 row per location 66 | lc <- lc %>% 67 | rasterToPoints %>% 68 | as.data.frame() %>% 69 | filter(lc != 0) # only retain pixels with a value 70 | 71 | #---- plotting outline ----- 72 | 73 | # setup the ggplot 74 | p <- ggplot() + 75 | 76 | # first layer is the land mass outline 77 | # as a grey border (fancy) 78 | geom_sf(data = land, 79 | fill = NA, 80 | color = "grey50", 81 | fill = "#dfdfdf", 82 | lwd = 1) + 83 | 84 | # crop the whole thing to size 85 | coord_sf(xlim = c(-30, 50), 86 | ylim = c(20, 70)) 87 | 88 | ggsave("output/01.png", width = 5, height = 5) 89 | 90 | p <- p + 91 | 92 | # second layer are the countries 93 | # with a white outline and and a 94 | # grey fill 95 | geom_sf(data = countries, 96 | color = "white", 97 | fill = "#dfdfdf", 98 | size = 0.2) + 99 | 100 | # crop the whole thing to size 101 | coord_sf(xlim = c(-30, 50), 102 | ylim = c(20, 70)) 103 | 104 | ggsave("output/02.png", width = 5, height = 5) 105 | 106 | p <- p + 107 | 108 | # then add the tree pixels 109 | # as tiles in green 110 | geom_tile(data = lc, 111 | aes(x = x, 112 | y = y), 113 | col = "darkolivegreen4") + 114 | 115 | # crop the whole thing to size 116 | coord_sf(xlim = c(-30, 50), 117 | ylim = c(20, 70)) 118 | 119 | ggsave("output/03.png", width = 5, height = 5) 120 | 121 | p <- p + 122 | # overlay the country borders 123 | # to cover the tree pixels 124 | # fill = NA to not overplot 125 | geom_sf(data = countries, 126 | color = "white", 127 | fill = NA, 128 | size = 0.2) + 129 | 130 | # crop the whole thing to size 131 | coord_sf(xlim = c(-30, 50), 132 | ylim = c(20, 70)) 133 | 134 | 135 | ggsave("output/04.png", width = 5, height = 5) 136 | 137 | p <- p + 138 | 139 | # add the locations of the sites 140 | # as a point 141 | geom_point(data = df, 142 | aes(lon, lat), 143 | col = "grey20") + 144 | 145 | # use ggrepel to add fancy 146 | # labels nudged to a 147 | # longitude of -25 148 | geom_text_repel( 149 | data = df, 150 | aes(lon, 151 | lat, 152 | label = site), 153 | nudge_x = -25 - df$lon, 154 | direction = "y", 155 | hjust = 0, 156 | segment.size = 0.2, 157 | seed = 1 # ensures the placing is consistent between renders 158 | ) + 159 | 160 | # crop the whole thing to size 161 | coord_sf(xlim = c(-30, 50), 162 | ylim = c(20, 70)) 163 | 164 | ggsave("output/05.png", width = 5, height = 5) 165 | 166 | p <- p + 167 | 168 | # add labels here if needed 169 | labs(x = NULL, 170 | y = NULL, 171 | title = "", 172 | subtitle = "", 173 | caption = "") + 174 | 175 | # crop the whole thing to size 176 | coord_sf(xlim = c(-30, 50), 177 | ylim = c(20, 70)) 178 | 179 | ggsave("output/06.png", width = 5, height = 5) 180 | 181 | p <- p + 182 | 183 | # apply the map theme as created above 184 | theme_map() 185 | 186 | # save the final plot 187 | ggsave("output/07.png", width = 5, height = 5) 188 | 189 | # you can animate the plot using imagemagick and the following command: 190 | # convert -delay 100 -loop 0 *.png map.gif 191 | 192 | 193 | -------------------------------------------------------------------------------- /map_building_1/map_building_1.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | -------------------------------------------------------------------------------- /map_building_1/modis_land_cover.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/modis_land_cover.tif -------------------------------------------------------------------------------- /map_building_1/output/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/01.png -------------------------------------------------------------------------------- /map_building_1/output/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/02.png -------------------------------------------------------------------------------- /map_building_1/output/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/03.png -------------------------------------------------------------------------------- /map_building_1/output/04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/04.png -------------------------------------------------------------------------------- /map_building_1/output/05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/05.png -------------------------------------------------------------------------------- /map_building_1/output/07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/07.png -------------------------------------------------------------------------------- /map_building_1/output/map.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_1/output/map.gif -------------------------------------------------------------------------------- /map_building_2/map.R: -------------------------------------------------------------------------------- 1 | # Dealing with raster resolution problems 2 | # when mixing raster and vector data. 3 | 4 | # load libraries 5 | library(raster) 6 | library(tidyverse) 7 | library(rnaturalearth) 8 | 9 | # grab country outlines / ocean areas as sf object 10 | countries <- ne_countries(returnclass = "sf", scale = 50) 11 | 12 | # create a fake coarse grid raster 13 | # with a "EU" extent 14 | r <- matrix(rnorm(100),10,10) 15 | r <- raster(r) 16 | extent(r) <- c(-20,20,30,70) 17 | 18 | # convert raster to dataframe 19 | # for ggplot2 plotting 20 | r_df <- r %>% 21 | rasterToPoints %>% 22 | as.data.frame() %>% 23 | filter(layer!=0) 24 | 25 | p <- ggplot() + 26 | geom_raster(data = r_df, 27 | aes(x = x, 28 | y = y, 29 | fill = layer)) + 30 | scale_fill_continuous() + 31 | 32 | geom_sf(data = countries, 33 | color = "white", 34 | fill = NA, 35 | size = 0.2) + 36 | 37 | # crop 38 | coord_sf(xlim = c(-20, 20), 39 | ylim = c(30, 70)) 40 | 41 | ggsave("output/01.png", width = 5, height = 5) 42 | 43 | # mask these values using the countries 44 | # and convert to dataframe for ggplot2 45 | # plotting 46 | r_m <- mask(r, countries) 47 | r_m_df <- r_m %>% 48 | rasterToPoints %>% 49 | as.data.frame() %>% 50 | filter(layer!=0) 51 | 52 | 53 | p <- ggplot() + 54 | geom_raster(data = r_m_df, 55 | aes(x = x, 56 | y = y, 57 | fill = layer)) + 58 | scale_fill_continuous() + 59 | 60 | geom_sf(data = countries, 61 | color = "white", 62 | fill = NA, 63 | size = 0.2) + 64 | 65 | # crop 66 | coord_sf(xlim = c(-20, 20), 67 | ylim = c(30, 70)) 68 | 69 | ggsave("output/02.png", width = 5, height = 5) 70 | 71 | # THE COVER UP 72 | # download ocean outlines 73 | ocean <- ne_download( 74 | scale = 50, 75 | type = "ocean", 76 | category = "physical", 77 | returnclass = "sf") 78 | 79 | # overplot the undesired coarse raster edges 80 | p <- ggplot() + 81 | geom_raster(data = r_df, 82 | aes(x = x, 83 | y = y, 84 | fill = layer)) + 85 | scale_fill_continuous() + 86 | 87 | geom_sf(data = ocean, 88 | color = NA, 89 | fill = "white", 90 | size = 0.2) + 91 | 92 | geom_sf(data = countries, 93 | color = "white", 94 | fill = NA, 95 | size = 0.2) + 96 | 97 | # crop the whole thing to size 98 | coord_sf(xlim = c(-20, 20), 99 | ylim = c(30, 70)) 100 | 101 | ggsave("output/03.png", width = 5, height = 5) 102 | 103 | # UPSAMPLE 100x and mask, then 104 | # convert to data frame 105 | r_u <- disaggregate(r, 100) 106 | r_u <- mask(r_u, countries) 107 | r_u_df <- r_u %>% 108 | rasterToPoints %>% 109 | as.data.frame() %>% 110 | filter(layer!=0) 111 | 112 | p <- ggplot() + 113 | geom_raster(data = r1_df, 114 | aes(x = x, 115 | y = y, 116 | fill = layer)) + 117 | scale_fill_continuous() + 118 | 119 | geom_sf(data = countries, 120 | color = "white", 121 | fill = NA, 122 | size = 0.2) + 123 | 124 | # crop the whole thing to size 125 | coord_sf(xlim = c(-20, 20), 126 | ylim = c(30, 70)) 127 | 128 | ggsave("output/04.png", width = 5, height = 5) 129 | 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /map_building_2/map_building_2.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /map_building_2/output/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_2/output/01.png -------------------------------------------------------------------------------- /map_building_2/output/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_2/output/02.png -------------------------------------------------------------------------------- /map_building_2/output/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_2/output/03.png -------------------------------------------------------------------------------- /map_building_2/output/04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_2/output/04.png -------------------------------------------------------------------------------- /map_building_3/data/00_download_data.R: -------------------------------------------------------------------------------- 1 | # load libraries 2 | library(ecmwfr) 3 | 4 | # the request to be made to grab the 5 | # required monthly data 6 | request <- list( 7 | format = "netcdf", 8 | product_type = "monthly_averaged_reanalysis", 9 | variable = c("2m_temperature", 10 | "downward_uv_radiation_at_the_surface"), 11 | time = "00:00", 12 | month = c("01", "02", "03", "04", 13 | "05", "06", "07", "08", 14 | "09", "10", "11", "12"), 15 | year = "2020", 16 | dataset_short_name = "reanalysis-era5-single-levels-monthly-means", 17 | target = "uv_temp.nc" 18 | ) 19 | 20 | # requires preset credentials using 21 | # wf_set_key(), see ecmwfr docs 22 | wf_request( 23 | request = request, 24 | user = "2088", 25 | path = "data/" 26 | ) 27 | 28 | -------------------------------------------------------------------------------- /map_building_3/data/uv_temp.nc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_3/data/uv_temp.nc -------------------------------------------------------------------------------- /map_building_3/drink_or_rub.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_3/drink_or_rub.png -------------------------------------------------------------------------------- /map_building_3/map.R: -------------------------------------------------------------------------------- 1 | # Mock bivariate map example 2 | 3 | # load tidyverse 4 | library(tidyverse) 5 | library(raster) 6 | library(rnaturalearth) 7 | library(sf) 8 | library(patchwork) 9 | 10 | # custom fonts 11 | library(showtext) 12 | font_add_google("Prata", regular.wt = 400) 13 | showtext_auto() 14 | 15 | # set robinson projection 16 | robinson <- CRS("+proj=robin +over") 17 | 18 | # read in raster data 19 | 20 | # max monthly UV data (scaled by seconds in a day 21 | # and referenced by a location in Belgium 22 | # assuming UV max values of around 10 in 23 | # this region) 24 | u <- brick("data/uv_temp.nc", varname = "uvb") 25 | u <- (max(u/(24*60*60), na.rm = TRUE)/ 32) * 10 26 | u <- rotate(u) 27 | 28 | # max yearly monthly temperature converted to C 29 | # from K 30 | t <- brick("data/uv_temp.nc", varname = "t2m") 31 | t <- max(t) - 273.15 32 | t <- rotate(t) 33 | 34 | # download countries 35 | countries <- ne_countries(scale = 50, returnclass = c("sf")) 36 | 37 | # create a bounding box for the robinson projection 38 | # we'll use this as "trim" to remove jagged edges at 39 | # end of the map (due to the curved nature of the 40 | # robinson projection) 41 | bb <- sf::st_union(sf::st_make_grid( 42 | st_bbox(c(xmin = -180, 43 | xmax = 180, 44 | ymax = 90, 45 | ymin = -90), crs = st_crs(4326)), 46 | n = 100)) 47 | bb_robinson <- st_transform(bb, as.character(robinson)) 48 | 49 | # transform the coastline to robinson 50 | countries_robinson <- st_transform(countries, robinson) 51 | 52 | # convert gridded raster dato dataframe 53 | u_df <- u %>% 54 | projectRaster(., res=50000, crs = robinson) %>% 55 | rasterToPoints %>% 56 | as.data.frame() %>% 57 | `colnames<-`(c("x", "y", "uv")) 58 | 59 | t_df <- t %>% 60 | projectRaster(., res=50000, crs = robinson) %>% 61 | rasterToPoints %>% 62 | as.data.frame() %>% 63 | `colnames<-`(c("x", "y", "temp")) 64 | 65 | # reclassify data using threshold values 66 | # so we get 3 classes for each layer 67 | u_df <- u_df %>% 68 | mutate( 69 | val = ifelse(uv <= 10, "1", 70 | ifelse(uv >= 12, "3", 71 | "2")) 72 | ) 73 | 74 | t_df <- t_df %>% 75 | mutate( 76 | val = ifelse(temp <= 10, "1", 77 | ifelse(temp >= 28, "3", 78 | "2")) 79 | ) 80 | 81 | # bind data by location and group 82 | # by the value (index) created above 83 | df <- left_join(t_df, u_df, by = c("x","y")) %>% 84 | mutate( 85 | group = paste(val.y, val.x, sep = " - ") 86 | ) %>% 87 | dplyr::select(-c(val.x, val.y)) 88 | 89 | # create a bivariate legend with indices 90 | # matching those created above 91 | legend_3 <- tibble( 92 | "3 - 3" = "#3F2949", # high UV, high temp 93 | "2 - 3" = "#435786", 94 | "1 - 3" = "#4885C1", # low UV, high temp 95 | "3 - 2" = "#77324C", 96 | "2 - 2" = "#806A8A", # medium UV, medium temp 97 | "1 - 2" = "#89A1C8", 98 | "3 - 1" = "#AE3A4E", # high UV, low temp 99 | "2 - 1" = "#BC7C8F", 100 | "1 - 1" = "#CABED0" # low UV, low temp 101 | ) %>% 102 | gather("group", "fill") 103 | 104 | # match the group constructed 105 | # above with the colour scheme 106 | # with 3 categories this is the 107 | # plotting dataframe 108 | df <- left_join(df, legend_3) 109 | 110 | # create the main map 111 | p1 <- ggplot()+ 112 | geom_raster( 113 | data = df, 114 | aes( 115 | x=x, 116 | y=y, 117 | fill=fill 118 | ), 119 | interpolate = TRUE 120 | ) + 121 | scale_fill_identity() + 122 | geom_sf(data=countries_robinson, 123 | colour='grey25', 124 | linetype='solid', 125 | fill= NA, 126 | size=0.3) + 127 | geom_sf(data=bb_robinson, 128 | colour='white', 129 | linetype='solid', 130 | fill = NA, 131 | size=0.7) + 132 | labs( 133 | title = "Liquids: drink it, or rub it!", 134 | subtitle = "Do you always need water & sunscreen?", 135 | caption = " 136 | Data: Copernicus Climate Data Store - 2020 137 | Temperature thresholds: low < 10C < mid < 28C < high 138 | Max seasonal UV Thresholds: normal < 10 < mid < 12 < high 139 | " 140 | ) + 141 | theme_void() + 142 | theme(legend.position = 'none', 143 | plot.subtitle = element_text( 144 | color = "grey30", 145 | size = 40, 146 | hjust = 0.1), 147 | plot.title = element_text( 148 | family = "Prata", 149 | color = "grey30", 150 | size = 70, 151 | hjust = 0.1), 152 | plot.caption = element_text( 153 | color = "grey30", 154 | size = 25, 155 | lineheight = 0.3), 156 | plot.margin = margin(r = 10) 157 | ) 158 | 159 | # create the legend 160 | p2 <- legend_3 %>% 161 | separate(group, 162 | into = c("uv", "temp"), 163 | sep = " - ") %>% 164 | mutate(temp = as.integer(temp), 165 | uv = as.integer(uv)) %>% 166 | ggplot() + 167 | geom_tile(mapping = aes( 168 | x = uv, 169 | y = temp, 170 | fill = fill)) + 171 | scale_fill_identity() + 172 | labs(x = "sunscreen →", 173 | y = "hydrate →") + 174 | theme_void() + 175 | theme( 176 | axis.title = element_text( 177 | size = 25, 178 | ), 179 | axis.title.y = element_text(angle = 90)) + 180 | coord_fixed() 181 | 182 | # create a layout to plot both 183 | # the main figure and the legend 184 | layout <- c( 185 | area(t = 1, l = 1, b = 7, r = 7), 186 | area(t = 1, l = 6, b = 1, r = 7) 187 | ) 188 | 189 | # create final layout 190 | p <- p1 + p2 + 191 | plot_layout(design = layout) 192 | 193 | # save the plot 194 | ggsave("drink_or_rub.png", width = 11) 195 | -------------------------------------------------------------------------------- /map_building_3/mapping_example.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /map_building_4/animation.R: -------------------------------------------------------------------------------- 1 | # load libraries 2 | library("raster") 3 | library("tidyverse") 4 | library("rnaturalearth") 5 | library("sf") 6 | library("gganimate") 7 | library("gifski") 8 | 9 | # custom fonts 10 | library(showtext) 11 | font_add_google("Prata", regular.wt = 400) 12 | showtext_auto() 13 | 14 | # set coordinate systems 15 | robinson <- CRS("+proj=robin +over") 16 | 17 | # create a bounding box for the robinson projection 18 | bb <- sf::st_union(sf::st_make_grid( 19 | st_bbox(c(xmin = -179.999, 20 | xmax = 179.999, 21 | ymax = 90, 22 | ymin = -1), crs = st_crs(4326)), 23 | n = 100)) 24 | bb_robinson <- st_transform(bb, as.character(robinson)) 25 | 26 | # download global coastline data from naturalearth 27 | countries <- ne_countries(scale = 110, returnclass = c("sf")) 28 | 29 | # clip countries to bounding box 30 | # and transform 31 | countries_robinson <- countries %>% 32 | st_buffer(0) %>% 33 | st_intersection(st_union(bb)) %>% 34 | st_transform(robinson) 35 | 36 | # load the grid data using raster 37 | g <- stack("data/carbon.nc") 38 | 39 | # convert gridded raster data dataframe 40 | g_df <- g %>% 41 | projectRaster(., res=50000, crs = robinson) %>% 42 | rasterToPoints %>% 43 | as.data.frame() %>% 44 | `colnames<-`(c("x", "y", names(g))) %>% 45 | pivot_longer(cols = starts_with("X20"), 46 | names_to = "layer", 47 | values_to = "val") %>% 48 | mutate(layer = substr(layer, 2, 14)) %>% 49 | mutate(date = as.POSIXct(layer, "%Y.%m.%d.%H", tz = "UTC") 50 | ) 51 | 52 | # formulate graphing element 53 | world_map <- ggplot() + 54 | theme_void() + 55 | geom_tile( 56 | data = g_df, 57 | aes( 58 | x = x, 59 | y = y, 60 | fill = log(val), 61 | group = date)) + 62 | scale_fill_viridis_c( 63 | option = "B" 64 | ) + 65 | geom_sf(data=countries_robinson, 66 | colour='white', 67 | linetype='solid', 68 | fill = NA, 69 | size=0.2) + 70 | geom_sf(data=bb_robinson, 71 | colour='white', 72 | linetype='solid', 73 | fill = NA, 74 | size= 1) + 75 | coord_sf(ylim = c(-17309.98, 8582690)) + 76 | theme( 77 | plot.title = element_text( 78 | family = "Prata", 79 | #color = "grey30", 80 | size = 50, 81 | hjust = 0.5), 82 | plot.subtitle = element_text( 83 | hjust = 0.5, 84 | size = 25), 85 | plot.caption = element_text( 86 | color = "grey50", 87 | size = 12, 88 | hjust = 0.9), 89 | legend.position = "none" 90 | ) + 91 | labs( 92 | title = "Fire season", 93 | subtitle = "", 94 | caption = "Data source: Copernicus ADS at {current_frame}") + 95 | transition_manual(date) 96 | 97 | #animate the plot 98 | gganimate::animate(world_map, 99 | width = 1000, 100 | height = 400, 101 | renderer=gifski_renderer("map.gif")) 102 | -------------------------------------------------------------------------------- /map_building_4/data/00_download_data.R: -------------------------------------------------------------------------------- 1 | options(keyring_backend="file") 2 | 3 | # load libraries 4 | library("ecmwfr") 5 | 6 | request <- list( 7 | date = "2021-07-21/2021-07-21", 8 | type = "forecast", 9 | format = "netcdf_zip", 10 | variable = "black_carbon_aerosol_optical_depth_550nm", 11 | time = "00:00", 12 | leadtime_hour = as.character(1:120), 13 | area = c(90, -180, 0, 180), 14 | dataset_short_name = "cams-global-atmospheric-composition-forecasts", 15 | target = "download.zip" 16 | ) 17 | 18 | # download the data (file location is returned) 19 | file <- wf_request(request, 20 | user = "2161") 21 | 22 | # unzip zip file (when multiples are called this will be zipped) 23 | unzip(file, exdir = tempdir()) 24 | files <- list.files(tempdir(), "*.nc", full.names = TRUE) 25 | 26 | # copy files to data 27 | file.copy(files, "data/carbon.nc") 28 | -------------------------------------------------------------------------------- /map_building_4/map.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_4/map.gif -------------------------------------------------------------------------------- /map_building_4/map_building_4.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /map_building_4/video.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_4/video.mp4 -------------------------------------------------------------------------------- /map_building_5/data/00_download_data.R: -------------------------------------------------------------------------------- 1 | # load libraries 2 | library(ecmwfr) 3 | 4 | # if using a file based key store 5 | # uncomment (see ecmwfr documentation) 6 | # options(keyring_backend="file") 7 | 8 | request <- list( 9 | product_type = "reanalysis", 10 | format = "netcdf", 11 | variable = c( 12 | "10m_u_component_of_wind", 13 | "10m_v_component_of_wind", 14 | "mean_sea_level_pressure"), 15 | year = "2005", 16 | day = "28", 17 | month = "08", 18 | time = "12:00", 19 | area = c(38, -104, 20, -73), 20 | dataset_short_name = "reanalysis-era5-single-levels", 21 | target = "wind.nc" 22 | ) 23 | 24 | # requires preset credentials using 25 | # wf_set_key(), see ecmwfr docs 26 | wf_request( 27 | request = request, 28 | user = "2088", 29 | path = "data/" 30 | ) 31 | 32 | -------------------------------------------------------------------------------- /map_building_5/data/wind.nc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_5/data/wind.nc -------------------------------------------------------------------------------- /map_building_5/map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bluegreen-labs/R_tutorials/3a065044093e2b4be9c9e1cdbbe9b05986e545da/map_building_5/map.png -------------------------------------------------------------------------------- /map_building_5/map_building_5.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /map_building_5/wind_map.R: -------------------------------------------------------------------------------- 1 | # read in libraries 2 | library(tidyverse) 3 | library(raster) 4 | library(metR) 5 | library(rnaturalearth) 6 | 7 | theme_map <- function(...) { 8 | theme_minimal() + 9 | theme( 10 | legend.key = element_rect(fill = "white", size = 1), 11 | legend.key.size = unit(0.5, "cm"), 12 | legend.key.width = unit(2.5, "cm"), 13 | legend.margin = margin(10, 10, 10, 10), 14 | legend.text = element_text( 15 | size = 10, 16 | angle = 45, 17 | vjust = 1, 18 | hjust = 1), 19 | legend.position = "bottom", 20 | axis.line = element_blank(), 21 | panel.grid.major = element_blank(), 22 | panel.grid.minor = element_blank(), 23 | plot.background = element_rect(fill = "#ffffff", color = NA), 24 | panel.background = element_rect(fill = "#ffffff", color = NA), 25 | legend.background = element_rect(fill = "#ffffff", color = NA), 26 | text = element_text(family = "Montserrat", color = "grey30", size=12), 27 | panel.border = element_blank(), 28 | plot.margin = margin(5, 0, 5, 0), 29 | axis.title.y = element_text(face = "bold", vjust = 10), 30 | axis.title.x = element_text(face = "bold", vjust = -2), 31 | panel.spacing = unit(1, "lines"), 32 | ... 33 | ) 34 | } 35 | 36 | # coastline sf object 37 | land <- ne_coastline( 38 | scale = 50, 39 | returnclass = "sf") 40 | 41 | # convert pressure 42 | pressure <- raster::raster( 43 | "data/wind.nc", 44 | varname = "msl" 45 | ) %>% 46 | rasterToPoints() %>% 47 | as.data.frame() %>% 48 | rename( 49 | 'lat' = 'y', 50 | 'lon' = 'x', 51 | 'pressure' = 'Mean.sea.level.pressure' 52 | ) %>% 53 | pivot_longer( 54 | cols = "pressure", 55 | names_to = "layer", 56 | values_to = "pressure" 57 | ) %>% 58 | mutate( 59 | pressure = pressure / 100 60 | ) 61 | 62 | # convert wind 63 | u <- raster::raster("data/wind.nc", 64 | varname = "u10") %>% 65 | rasterToPoints() %>% 66 | as.data.frame() %>% 67 | rename( 68 | 'lat' = 'y', 69 | 'lon' = 'x', 70 | 'u' = starts_with("X10") 71 | ) %>% 72 | pivot_longer( 73 | cols = "u", 74 | names_to = "layer", 75 | values_to = "u" 76 | ) %>% 77 | dplyr::select(-layer) 78 | 79 | v <- raster::raster( 80 | "data/wind.nc", 81 | varname = "v10") %>% 82 | rasterToPoints() %>% 83 | as.data.frame() %>% 84 | rename( 85 | 'lat' = 'y', 86 | 'lon' = 'x', 87 | 'v' = starts_with("X10") 88 | ) %>% 89 | pivot_longer( 90 | cols = "v", 91 | names_to = "layer", 92 | values_to = "v" 93 | ) %>% 94 | dplyr::select(-layer) 95 | 96 | wind <- left_join(u, v) 97 | 98 | p <- ggplot() + 99 | geom_contour_fill( 100 | data = pressure, 101 | aes( 102 | lon, 103 | lat, 104 | z = pressure, 105 | fill = stat(level) 106 | ), 107 | breaks = MakeBreaks(3) 108 | ) + 109 | geom_sf(data = land, 110 | color = "white", 111 | fill = NA, 112 | size = 1.2 113 | ) + 114 | geom_sf(data = land, 115 | color = "grey50", 116 | fill = NA, 117 | size = 0.4 118 | ) + 119 | metR::geom_streamline( 120 | data = wind, 121 | aes(x = lon, 122 | y = lat, 123 | dx = u, 124 | dy = v, 125 | alpha = ..step.. 126 | ), 127 | color = "grey", 128 | size = 0.4, 129 | L = 2, 130 | res = 2, 131 | n = 30, 132 | arrow = NULL, 133 | lineend = "round", 134 | inherit.aes = FALSE) + 135 | scale_alpha(guide = "none") + 136 | scale_fill_divergent_discretised( 137 | high = "#7f3b08", 138 | mid = "#f7f7f7", 139 | low = "#2d004b", 140 | name = "mean sea leavel pressure (hPa) \n \n ", 141 | midpoint = 984 142 | ) + 143 | labs( 144 | title = "Hurricane Katrina", 145 | subtitle = "peak intensity at August 28, 2005", 146 | x = "", 147 | y = "" 148 | ) + 149 | coord_sf(xlim = c(-95, -75), 150 | ylim = c(36, 23)) + 151 | theme_map() 152 | 153 | print(p) 154 | ggsave("map.png", height = 8, width = 9) 155 | --------------------------------------------------------------------------------