Tarefa4

Author

Licet Fernanda Calambás Trochez

Published

June 6, 2023

#####Exercício 1: Utilizando qualquer recurso apresentado em aula, faça um mapa destacando ou mostrando o estado e município que você nasceu.

library(rgdal)
Loading required package: sp
Please note that rgdal will be retired during 2023,
plan transition to sf/stars/terra functions using GDAL and PROJ
at your earliest convenience.
See https://r-spatial.org/r/2022/04/12/evolution.html and https://github.com/r-spatial/evolution
rgdal: version: 1.6-6, (SVN revision 1201)
Geospatial Data Abstraction Library extensions to R successfully loaded
Loaded GDAL runtime: GDAL 3.6.2, released 2023/01/02
Path to GDAL shared files: C:/Users/lisa1/AppData/Local/R/win-library/4.3/rgdal/gdal
 GDAL does not use iconv for recoding strings.
GDAL binary built with GEOS: TRUE 
Loaded PROJ runtime: Rel. 9.2.0, March 1st, 2023, [PJ_VERSION: 920]
Path to PROJ shared files: C:/Users/lisa1/AppData/Local/R/win-library/4.3/rgdal/proj
PROJ CDN enabled: FALSE
Linking to sp version:1.6-0
To mute warnings of possible GDAL/OSR exportToProj4() degradation,
use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
library(ggplot2)
library(maptools)
Checking rgeos availability: TRUE
Please note that 'maptools' will be retired during 2023,
plan transition at your earliest convenience;
some functionality will be moved to 'sp'.
library(plyr)
library(sp)
library(raster)
library(dismo)
library (rgdal)

setwd("C:/Users/lisa1/Documents/UFPR/Doutorado/Disci_dados_R/")
col_dpto <-shapefile("shapefiles_colombia/depto.shp")

class(col_dpto)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
slotNames(col_dpto)
[1] "data"        "polygons"    "plotOrder"   "bbox"        "proj4string"
col_dpto@data$id = rownames(col_dpto@data)
departamentos.points <- fortify(col_dpto,region = "id")
rgeos version: 0.6-3, (SVN revision 696)
 GEOS runtime version: 3.11.2-CAPI-1.17.2 
 Please note that rgeos will be retired during October 2023,
plan transition to sf or terra functions using GEOS at your earliest convenience.
See https://r-spatial.org/r/2023/05/15/evolution4.html for details.
 GEOS using OverlayNG
 Linking to sp version: 1.6-0 
 Polygon checking: TRUE 
departamentos.df <- join(departamentos.points,col_dpto@data,by = "id")
head(departamentos.df)
      long     lat order  hole piece id group DPTO NOMBRE_DPT        AREA
1 754872.1 1445317     1 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
2 755883.0 1444990     2 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
3 756588.8 1445107     3 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
4 758291.0 1444135     4 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
5 759752.5 1443540     5 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
6 760958.2 1442437     6 FALSE     1  1   1.1   05  ANTIOQUIA 63351855547
  PERIMETER HECTARES
1   1963729  6335186
2   1963729  6335186
3   1963729  6335186
4   1963729  6335186
5   1963729  6335186
6   1963729  6335186
class(departamentos.df)
[1] "data.frame"
library(maps)

Attaching package: 'maps'
The following object is masked from 'package:plyr':

    ozone
library(ggmap)
ℹ Google's Terms of Service: <https://mapsplatform.google.com>
ℹ Please cite ggmap if you use it! Use `citation("ggmap")` for details.

Attaching package: 'ggmap'
The following object is masked from 'package:dismo':

    geocode
colombia <- ggplot(departamentos.df) + 
  aes(long,lat,group=group) + 
  geom_polygon(fill= "lightgray") +
  geom_path(color="white") +
  coord_equal() +
  theme_void()+
  theme(legend.position = "none")
colombia

library(rgdal)
library(ggplot2)
library(maptools)
library(plyr)
library(sp)
library(raster)
library(dismo)
library (rgdal)

setwd("C:/Users/lisa1/Documents/UFPR/Doutorado/Disci_dados_R/")
col_mun <-shapefile("shapefiles_colombia/mpio.shp")

class(col_mun)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
slotNames(col_mun)
[1] "data"        "polygons"    "plotOrder"   "bbox"        "proj4string"
col_mun@data$id = rownames(col_mun@data)
municipios.points <- fortify(col_mun,region = "id")


#transformar o shape de municipios em dataframe
municipios.df <- join(municipios.points,col_mun@data,by = "id")

library(maps)
library(ggmap)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ lubridate 1.9.2     ✔ tibble    3.2.1
✔ purrr     1.0.1     ✔ tidyr     1.3.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::arrange()   masks plyr::arrange()
✖ purrr::compact()   masks plyr::compact()
✖ dplyr::count()     masks plyr::count()
✖ dplyr::desc()      masks plyr::desc()
✖ tidyr::extract()   masks raster::extract()
✖ dplyr::failwith()  masks plyr::failwith()
✖ dplyr::filter()    masks stats::filter()
✖ dplyr::id()        masks plyr::id()
✖ dplyr::lag()       masks stats::lag()
✖ purrr::map()       masks maps::map()
✖ dplyr::mutate()    masks plyr::mutate()
✖ dplyr::rename()    masks plyr::rename()
✖ dplyr::select()    masks raster::select()
✖ dplyr::summarise() masks plyr::summarise()
✖ dplyr::summarize() masks plyr::summarize()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
dpto<-ggplot(filter(municipios.df, NOMBRE_DPT=="CAUCA")) + 
  aes(long,lat,group=group) + 
  geom_polygon(fill="lightgreen") +
  geom_path(color="white") +
  coord_equal() +
  theme_void()+
  theme(legend.position = "none")
dpto

mpio<-ggplot(filter(municipios.df, id=="917")) + 
  aes(long,lat,group=group) + 
  geom_polygon(fill="lightblue") +
  geom_path(color="white") +
  coord_equal() +
  theme_void()+
  theme(legend.position = "none")
mpio

library(cowplot)#para fazer paineis

Attaching package: 'cowplot'

The following object is masked from 'package:lubridate':

    stamp

The following object is masked from 'package:ggmap':

    theme_nothing
library(jpeg)
setwd("C:/Users/lisa1/Documents/UFPR/Doutorado/Disci_dados_R/")
img3 <- readJPEG("cafe3.jpg")
cafe<-as.raster(img3)

img<-readJPEG("flecha.jpg")
imgr<-as.raster(img)
imgr2<-imgr

ggdraw()+
  coord_equal(xlim = c(0,40),ylim = c(0,40))+
  annotation_custom(ggplotGrob(mpio),xmin=30,xmax=40, ymin=0,ymax=18)+
  annotation_custom(ggplotGrob(dpto),xmin=15,xmax=27, ymin=10,ymax=25)+
  annotation_custom(ggplotGrob(colombia),xmin=0,xmax=12,ymin = 10,ymax=40)+
  annotation_raster(cafe,xmin =30,xmax = 40,ymin=25,ymax=35)+
  annotation_raster(imgr,xmin =12,xmax = 16,ymin=18,ymax=22)+
  annotation_raster(imgr2,xmin =25,xmax = 30,ymin=10,ymax=15)
Coordinate system already present. Adding new coordinate system, which will
replace the existing one.

#####Exercício 2: Utilizando os recursos do banco de dados do GBIF e utilizando o pacote rgbif, apresente a localização de alguma espécie que você estude ou goste. Lembre-se que se a distribuição é muito ampla, os dados vão demorar a carregar, então limitar o número de observações ou escolher uma espécie de distribuição restrita pode ser uma opção!

library(tidyverse)
library(ggmap)
library(maps)##tem alguns mapas já previamente feitos
library(rgbif)
ocorrencia<-occ_search(scientificName="Butia exilata", hasCoordinate=T)

local<-as.data.frame(ocorrencia$data)
library(jpeg)
setwd("C:/Users/lisa1/Documents/UFPR/Doutorado/Disci_dados_R/")
butia <- readJPEG("butia_exilata.jpg")
butiar<-as.raster(butia)
library(geobr)
Loading required namespace: sf
biomas <- read_biomes(year=2019, showProgress = FALSE)
Using year 2019
head(biomas)
Simple feature collection with 6 features and 3 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -73.98304 ymin: -33.75115 xmax: -28.84785 ymax: 5.269581
Geodetic CRS:  SIRGAS 2000
      name_biome code_biome year                           geom
1       Amazônia          1 2019 MULTIPOLYGON (((-44.08515 -...
2       Caatinga          2 2019 MULTIPOLYGON (((-41.7408 -2...
3        Cerrado          3 2019 MULTIPOLYGON (((-43.39009 -...
4 Mata Atlântica          4 2019 MULTIPOLYGON (((-48.70814 -...
5          Pampa          5 2019 MULTIPOLYGON (((-52.82472 -...
6       Pantanal          6 2019 MULTIPOLYGON (((-57.75946 -...
library(ggsn)#para colocar barra do norte
Loading required package: grid

Attaching package: 'ggsn'
The following object is masked from 'package:raster':

    scalebar
#Fazendo mapa
ggplot()+ borders("world", fill = "orchid", colour = "gray",alpha=0.5)+
    geom_sf(data= filter(biomas,name_biome=="Mata Atlântica"),  aes(fill=name_biome, alpha=0.7)) +
    geom_point(data = local,aes(decimalLongitude,y=decimalLatitude),color="red",size=2,alpha=0.5)+
    annotation_raster(butiar,-40, -30,-30,-20)+
    scale_fill_manual(values = terrain.colors(7))+
    coord_sf(xlim= c(-80,-30), ylim=c(-40,10))+
    theme(legend.position = c(0.8,0.9), legend.background = element_blank(), legend.text=element_text(size=10),
          legend.title = element_blank(),
          legend.key.size = unit(0.4, "cm"),
          panel.grid.major = element_line(color = "darkgray", linetype = "dashed", size = 0.5), 
          panel.background = element_rect(fill = "aliceblue"),
          axis.title = element_blank())+
    guides(fill = guide_legend(nrow = 3), alpha= "none")+
    north(biomas, symbol = 14, location = "topleft") +
    scalebar(biomas, location = "bottomright", dist = 1000, dist_unit = "km",
             transform = TRUE, model = "WGS84")
Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
ℹ Please use the `linewidth` argument instead.

#####Exercício 3: Utilizando os dados de Numbats na Australia, faça um mapa de ocorrência nos diferentes anos.(um mapa ou vários mapas)

library(tidyverse)
library(ggplot2)
numbats <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-03-07/numbats.csv')
Rows: 805 Columns: 16
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (6): scientificName, taxonConceptID, recordID, dataResourceName, month,...
dbl  (7): decimalLatitude, decimalLongitude, year, hour, prcp, tmax, tmin
lgl  (1): dryandra
dttm (1): eventDate
date (1): day

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#write.table(numbats,"numbats.csv")

#Faço o mapa da regiao de estudo
mapa_aus<-map_data("world", region="Australia")

#Faco mapa da regiao de estudo mais pontos de ocorrencia
map_numbats<-ggplot(data=numbats, aes(x=decimalLongitude, y=decimalLatitude))+
  coord_equal()+
  geom_map(data=mapa_aus, map=mapa_aus, aes(x=long, y=lat, map_id=region), fill="brown",alpha=0.5, color="black")+
  stat_density2d(aes(fill = ..level..), alpha = .8,
                 geom = "polygon", data = numbats)+
  geom_point(aes(color=year))+
  facet_wrap(~year)+
  theme_void()+
  labs(title = "Pontos de corrência de numbats na Australia entre 1856-2023")+
  theme(axis.title = element_blank(),
        axis.text = element_blank(),
        legend.position = "none",
        plot.background = element_rect(fill="white", color=NA),
        panel.background = element_rect(fill="white", color=NA),
        strip.background = element_rect(fill="white", color="darkgray"),
      plot.title = element_text(size = 14, margin=margin(3,3,25,1)))
Warning in geom_map(data = mapa_aus, map = mapa_aus, aes(x = long, y = lat, :
Ignoring unknown aesthetics: x and y
map_numbats
Warning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(level)` instead.
Warning: Removed 83 rows containing non-finite values (`stat_density2d()`).
Warning: Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Caused by error in `if (any(h <= 0)) ...`:
! valor ausente donde TRUE/FALSE es necesario
Warning: Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Caused by error in `MASS::kde2d()`:
! bandwidths must be strictly positive
Warning: Computation failed in `stat_density2d()`
Caused by error in `if (any(h <= 0)) ...`:
! valor ausente donde TRUE/FALSE es necesario
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: Removed 83 rows containing missing values (`geom_point()`).

library(jpeg)
setwd("C:/Users/lisa1/Documents/UFPR/Doutorado/Disci_dados_R/")
numbat <- readJPEG("numbat2.jpg")
numbatr2<-as.raster(numbat)

library(cowplot)#para fazer paineis
ggdraw()+
  coord_equal(xlim = c(0,40),ylim = c(0,40))+
  annotation_custom(ggplotGrob(map_numbats),xmin=0,xmax=40, ymin=0,ymax=40)+annotation_raster(numbatr2,xmin =6.5,xmax = 18,ymin=1,ymax=9)
Coordinate system already present. Adding new coordinate system, which will
replace the existing one.
Warning: Removed 83 rows containing non-finite values (`stat_density2d()`).
Warning: Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Caused by error in `if (any(h <= 0)) ...`:
! valor ausente donde TRUE/FALSE es necesario
Warning: Computation failed in `stat_density2d()`
Computation failed in `stat_density2d()`
Caused by error in `MASS::kde2d()`:
! bandwidths must be strictly positive
Warning: Computation failed in `stat_density2d()`
Caused by error in `if (any(h <= 0)) ...`:
! valor ausente donde TRUE/FALSE es necesario
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: `stat_contour()`: Zero contours were generated
Warning in min(x): ningún argumento finito para min; retornando Inf
Warning in max(x): ningun argumento finito para max; retornando -Inf
Warning: Removed 83 rows containing missing values (`geom_point()`).

#####Exercício 4: Utilizando os dados de [Culturas agrícolas do passado, faça um mapa mostrando a ocorrência das diferentes famílias de culturas agrícolas. (um mapa ou vários mapas)

culturas <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-18/founder_crops.csv')
Rows: 4490 Columns: 24
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (18): source, source_id, source_site_name, site_name, phase, phase_descr...
dbl  (6): latitude, longitude, age_start, age_end, n, prop

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#write.table(culturas,"culturas.csv")

##mudo o nome das variáveis dentro da coluna category
culturas2<-mutate(culturas,`category`=recode(`category`, `Fruits/nuts`="Frutas/nueces", Grasses="Gramineas", Pulses="Leguminosas",`Wild plants`="Plantas selvagens"))

library(tidyverse)
library(ggplot2)

culturasgraf<-ggplot()+ borders("world", fill = "lightgray", colour = "gray")+
  geom_point(data = filter(culturas2, (!is.na(category))), aes(x= longitude, y= latitude, color=category), alpha=0.5)+
  coord_fixed(xlim=c(20, 60), ylim=c(20, 50))+
  facet_wrap(~category)+
  theme_void()+
  labs(title = "Culturas agrícolas do passado")+
  scale_fill_brewer(palette="YlGnBu")+
  theme(panel.grid = element_blank(), 
        plot.background = element_rect(fill = "#FFFFD9" , color=NA),
        plot.title = element_text(colour = "#081D58", size=18),
        legend.position="none",
        strip.background = element_rect(fill ="#FFFFD9"),
        strip.text = element_text(colour = "#081D58", size=14))
culturasgraf