O Bioma Stats é um pacote em R criado para facilitar o processamento e a análise de dados geoespaciais, com foco em uso e cobertura da terra (Land Use and Land Cover - LULC) no território brasileiro. O pacote foi desenvolvido para automatizar fluxos de trabalho complexos em análises ambientais, desde o download dos dados até a visualização dos resultados, sendo uma ferramenta acessível até para usuários iniciantes no R.The Bioma Stats is an R package created to facilitate the processing and analysis of geospatial data, with a focus on land use and land cover (LULC) across Brazilian territory. The package was developed to automate complex workflows in environmental analyses, from data download to results visualization, making it an accessible tool even for beginners in R.
Integra dados de fontes como o projeto MapBiomas e o OpenStreetMap, permitindo análises detalhadas de atributos espaciais como proximidade a rodovias e corpos d’água.Integrates data from sources such as the MapBiomas project and OpenStreetMap, enabling detailed analyses of spatial attributes such as proximity to roads and water bodies.
Cálculo de métricas como fragmentação, densidade de borda e evolução temporal do uso do solo, essenciais para estudos de conservação e planejamento ambiental.Calculation of metrics such as fragmentation, edge density, and temporal evolution of land use, essential for conservation studies and environmental planning.
Visualização de mapas LULC e análises customizadas em áreas de interesse, definidas por shapefiles ou polígonos desenhados pelo usuário.Visualization of LULC maps and customized analyses in areas of interest, defined by shapefiles or user-drawn polygons.
Exporta mapas recortados, tabelas de áreas,
métricas de paisagem e objetos .Rdata no padrão Bioma
Stats, prontos para uso imediato em R ou compartilhamento entre
pesquisadores.Exports clipped maps, area
tables, landscape metrics, and .Rdata objects in the Bioma
Stats standard, ready for immediate use in R or sharing among
researchers.
Download da coleção completa via
download_mapbiomas ou uso de coleções locais, sem
servidores intermediários.Download of the
full collection via download_mapbiomas or use of local
collections, without intermediate servers.
Com o Bioma Stats, o usuário pode automatizar várias etapas da análise ambiental, tornando o processo mais eficiente e menos suscetível a erros. O pacote é recomendado para pesquisadores de diversas áreas interessados em realizar análises ambientais com dados georreferenciados de maneira prática e intuitiva.With Bioma Stats, users can automate several steps of environmental analysis, making the process more efficient and less error-prone. The package is recommended for researchers from diverse fields interested in conducting environmental analyses with georeferenced data in a practical and intuitive way.
O Bioma Stats é disponibilizado apenas
na versão de teste e deve ser instalado diretamente do repositório do
GitHub (iep-ferreira/biomastats).The Bioma Stats is available only as a test
version and must be installed directly from the GitHub repository
(iep-ferreira/biomastats).
Para quem já instalou versões anteriores do programa, recomenda-se a remoção do pacote e a reinicialização da sessão do R.For those who have already installed earlier versions of the program, it is recommended to remove the package and restart the R session.
O pacote devtools é requerido para
a instalação do programa. Para instalar e carregar o pacote
devtools, use os comandos a seguir:The devtools package is required to install
the program. To install and load the devtools package, use
the following commands:
Após carregar o devtools, o
usuário deverá instalar e carregar o pacote
biomastats.After loading
devtools, the user must install and load the
biomastats package.
No programa Bioma Stats, o usuário pode
importar um recorte via polígono em .shp ou definir uma
área a partir de coordenadas centrais e da forma do recorte.In Bioma Stats, the user can import a study area via a
polygon .shp file or define an area from central
coordinates and the shape of the clip.
O usuário tem a opção de indicar o caminho do
shapefile a ser carregado. O próprio Bioma Stats contém
alguns exemplos de arquivos .shp alocados na subpasta
./biomastats/shp/, a qual é encontrada na biblioteca
pessoal do R após a instalação do programa. Para acessar o seu caminho,
utilize o comando system.file como ilustrado a
seguir:The user may specify the path of the
shapefile to be loaded. Bioma Stats itself contains some
example .shp files in the ./biomastats/shp/
subfolder, which is found in the personal R library after installing the
package. To access its path, use the system.file command as
illustrated below:
O recorte pode ser visualizado, antes da
análise, com auxílio dos pacotes sf e mapview.
No código a seguir, o arquivo .shp com as delimitações da
fazenda Lagoa do Sino, da UFSCar de Buri - SP, é carregado e
visualizado.The study area can be previewed
before analysis with the help of the sf and
mapview packages. In the code below, the .shp
file with the boundaries of the Lagoa do Sino farm at UFSCar Buri - SP
is loaded and visualized.
# install.packages("sf")
# install.packages("mapview")
library(sf)
library(mapview)
# O Leaflet trabalha com longitude/latitude; transforme o shapefile antes
# de calcular os limites para que o mapa seja enquadrado na área de estudo.
area_estudo <- sf::read_sf(ufscar_shp) |>
sf::st_transform(4326)
basemaps <- c(
"CartoDB.Positron", "CartoDB.DarkMatter", "OpenStreetMap",
"Esri.WorldImagery", "OpenTopoMap"
)
mapa_centrado <- function(x) {
bb <- sf::st_bbox(x)
mapview(x, map.types = basemaps)@map |>
leaflet::fitBounds(
lng1 = unname(bb["xmin"]), lat1 = unname(bb["ymin"]),
lng2 = unname(bb["xmax"]), lat2 = unname(bb["ymax"])
) |>
htmlwidgets::onRender(
"function(el, x) {
var map = this;
function ajustarMapa() {
map.invalidateSize();
map.fitBounds(
[[x.limits.lat[0], x.limits.lng[0]],
[x.limits.lat[1], x.limits.lng[1]]],
{ padding: [50, 50] }
);
}
map.whenReady(ajustarMapa);
setTimeout(ajustarMapa, 250);
}"
)
}
mapa_centrado(area_estudo)Outra forma de definir o recorte é a partir das
coordenadas centrais. Com as coordenadas centrais, a forma e o tamanho
do recorte desejados pelo pesquisador, a função
make_polygon do programa Bioma Stats é capaz de criar o
.shp automaticamente. Neste caso, o usuário deve informar a
latitude (lat), a longitude (lon), o diâmetro
(size, em km) e a forma desejada (shape =
circle, hexagon ou square), como
demonstrado a seguir:Another way to define
the study area is from central coordinates. With the central
coordinates, shape, and size desired by the researcher, the
make_polygon function in Bioma Stats can create the
.shp automatically. In this case, the user must provide
latitude (lat), longitude (lon), diameter
(size, in km), and desired shape (shape =
circle, hexagon, or square), as
shown below:
Neste exemplo, criou-se uma região hexagonal de
\(2{,}5\) km de diâmetro, centrada na
localização do campus Lagoa do Sino. Observe que o .shp foi
automaticamente salvo como polygon.shp no diretório
shp da biblioteca pessoal do R
biomastats.In this example, a
hexagonal region \(2.5\) km in diameter
was created, centered on the Lagoa do Sino campus location. Note that
the .shp was automatically saved as
polygon.shp in the shp directory of the
personal R library biomastats.
polygon_estudo <- sf::read_sf(file.path(path_package, "shp/polygon.shp")) |>
sf::st_transform(4326)
mapa_centrado(polygon_estudo)
Os dados de uso e ocupação do solo são
carregados e pré-processados pela função load_rasters. O
fluxo padrão tem duas etapas: (i) baixar a coleção completa do MapBiomas
para um diretório local e (ii) carregar, a partir desse diretório,
apenas o recorte de interesse. Como a coleção já se encontra baixada
neste computador, somente a segunda etapa é executada aqui.Land use and land cover data are loaded and
pre-processed by the load_rasters function. The standard
workflow has two steps: (i) download the full MapBiomas collection to a
local directory and (ii) load only the study area clip from that
directory. Since the collection is already downloaded on this computer,
only the second step is executed here.
O download dos mapas anuais é feito uma única
vez com a função download_mapbiomas, que obtém os arquivos
diretamente do repositório público do MapBiomas e os salva no diretório
indicado em dest_dir. Anos já presentes no diretório são
ignorados, evitando downloads duplicados. Recomenda-se
definir o caminho da coleção em uma variável, para reutilizá-lo nas
etapas seguintes.Annual maps are downloaded
once with the download_mapbiomas function, which retrieves
files directly from the public MapBiomas repository and saves them in
the directory specified in dest_dir. Years already present
in the directory are skipped, avoiding duplicate downloads.
It is recommended to define the collection path in a variable for reuse
in subsequent steps.
Como a coleção já está disponível localmente, o comando de download a seguir é apenas ilustrativo e não precisa ser executado novamente.Since the collection is already available locally, the download command below is illustrative only and does not need to be run again.
download_mapbiomas(dest_dir = path_collection_10, data_type = "cover",
collection = 10, time_range = c(1985, 2024))Com a coleção armazenada localmente, o recorte
é carregado com load_rasters usando method =
“library”. O usuário informa o caminho do shapefile
(shape_path), o intervalo de anos (start e
end), o caminho da pasta onde a coleção foi salva
(import_folder_path) e a coleção utilizada
(collection).With the
collection stored locally, the clip is loaded with
load_rasters using method = “library”. The
user provides the shapefile path (shape_path),
the year range (start and end), the path to
the folder where the collection was saved
(import_folder_path), and the collection used
(collection).
mapas <- load_rasters(
shape_path = ufscar_shp,
start = 1985, end = 2024,
method = "library",
import_folder_path = path_collection_10,
collection = 10
)Observe que o usuário deve sempre especificar
os anos de início (start) e fim (end) do
estudo. A Coleção 10 do MapBiomas, utilizada neste material, contém
mapas anuais de uso e ocupação do solo de 1985 a 2024.Note that the user must always specify the study start
year (start) and end year (end). MapBiomas
Collection 10, used in this material, contains annual land use and land
cover maps from 1985 to 2024.
Como load_rasters apenas recorta a
janela de interesse a partir dos arquivos nacionais, qualquer número de
recortes pode ser carregado localmente de forma rápida e sem novas
transferências pela internet.Because
load_rasters only crops the area of interest from the
national files, any number of clips can be loaded locally quickly and
without new internet transfers.
Os mapas pré-processados no Bioma Stats podem
ser exportados e distribuídos como objeto de dados do R
(Rdata). Dessa forma, os resultados podem ser
compartilhados com outros pesquisadores ou guardados para análises
futuras, evitando refazer o recorte da coleção.Pre-processed maps in Bioma Stats can be exported and
shared as R data objects (Rdata). This way, results can be
shared with other researchers or saved for future analyses, avoiding
redoing the collection clip.
Todas as informações relevantes são recuperadas
quando o usuário carrega o arquivo .Rdata, recuperando o
objeto mapas com todos os seus atributos:All relevant information is recovered when the user
loads the .Rdata file, restoring the mapas
object with all its attributes:
Os objetos do Bioma Stats possuem atributos
como horizonte de tempo (time_range), delimitações do
recorte (shape) e rasters recortados e reprojetados para
WGS84 (raster). Eles podem ser acessados diretamente,
usando o operador $.Bioma
Stats objects have attributes such as time range
(time_range), clip boundaries (shape), and
cropped rasters reprojected to WGS84 (raster). They can be
accessed directly using the $ operator.
## [1] 1985 2024
A função get_area do Bioma Stats
faz o cálculo de área das classes da paisagem e corrige o seu valor de
acordo com as coordenadas dos pixels. As áreas são exportadas na forma
de tabela estruturada, organizadas por classe da paisagem e
ano.The get_area function in
Bioma Stats calculates landscape class areas and corrects their values
according to pixel coordinates. Areas are exported as a structured table
organized by landscape class and year.
## land_class year area land_class_name
## 3 3 1985 0.524 Forest Formation
## 9 9 1985 0.008 Forest Plantation
## 11 11 1985 1.193 Wetland
## 12 12 1985 0.061 Grassland
## 15 15 1985 3.767 Pasture
## 21 21 1985 0.757 Mosaic of Uses
O atributo time_series do
resultado fornece ao usuário o gráfico de séries temporais para todas as
classes de uso e ocupação do solo existentes na paisagem. Há duas opções
para o gráfico das séries temporais: plot_type = “areaplot”
ou plot_type = “profile”.The
time_series attribute of the result provides the user with
a time series plot for all land use and land cover classes in the
landscape. There are two options for the time series plot:
plot_type = “areaplot” or plot_type =
“profile”.
Adicionalmente, o comando land_vis
permite ao usuário visualizar o mapa de uso e ocupação da área para o
ano de sua escolha. As cores e legendas seguem normas técnicas e foram
importadas da plataforma MapBiomas.Additionally, the land_vis command allows
the user to visualize the land use and land cover map for a chosen year.
Colors and legends follow technical standards and were imported from the
MapBiomas platform.
O comando land_dist apresenta a
distribuição de classes, em termos de área total, para o ano de
referência. As opções são gráfico de colunas (type =
“barplot”) e de pizza (type = “pie”).The land_dist command shows class
distribution in terms of total area for the reference year. Options are
column chart (type = “barplot”) and pie chart (type =
“pie”).
O Bioma Stats também apresenta um módulo para a
reclassificação e métricas da paisagem. O módulo é integrado com o
programa landscapemetrics do R e possui uso intuitivo: na
função biomastats_metrics, o usuário precisa passar o
objeto no padrão biomastats, o horizonte de tempo, a zona de fuso
horário, o hemisfério (“south” ou “north”) e
as métricas de interesse (“Frag. Avg. Area (ha)”,
“Edge Length (m)”, “Edge Density (m/ha)”,
“Total Reclassified Area (ha)”, “Aggregation Index
(%)”, “Number of Fragments”). Ao fazer metrics
= “keep.all”, todas as métricas existentes no programa serão
calculadas.Bioma Stats also provides a
module for reclassification and landscape metrics. The module is
integrated with the R landscapemetrics package and is
intuitive to use: in biomastats_metrics, the user must pass
the biomastats-standard object, the time range, the time zone, the
hemisphere (“south” or “north”), and metrics
of interest (“Frag. Avg. Area (ha)”, “Edge Length
(m)”, “Edge Density (m/ha)”, “Total
Reclassified Area (ha)”, “Aggregation Index (%)”,
“Number of Fragments”). With metrics =
“keep.all”, all metrics available in the program will be
calculated.
Por padrão (classes = NULL), o
programa abre uma janela seletora para a escolha interativa das classes
de uso e ocupação do solo. Para tornar a análise reprodutível, os
códigos das classes também podem ser informados diretamente no argumento
classes. No exemplo a seguir, selecionamos as classes
florestais Formação Florestal (código 3) e Formação Savânica (código
4).By default (classes =
NULL), the program opens a selector window for interactive choice
of land use and land cover classes. To make the analysis reproducible,
class codes can also be provided directly in the classes
argument. In the example below, we select the forest classes Forest
Formation (code 3) and Savanna Formation (code 4).
plot_teste <- biomastats_metrics(mapas, start = 1985, end = 2024, zone = "22",
hemisphere = "south", classes = c(3, 4),
metrics = "keep.all")As métricas são exportadas na forma de tabela,
como retorno da função biomastats_metrics:Metrics are exported as a table returned by
biomastats_metrics:
## Year Frag. Avg. Area (ha) Edge Length (m) Edge Density (m/ha)
## 1 1985 2.384525 17170.0 26.33257
## 2 1986 2.354625 16820.8 25.79702
## 3 1987 2.137850 17734.4 27.19815
## 4 1988 2.270125 17674.6 27.10644
## 5 1989 2.279875 16721.5 25.64473
## 6 1990 2.006290 17008.5 26.08489
## Total Reclassified Area (ha) Aggregation Index (%) Number of Fragments
## 1 52.45955 75.18367 22
## 2 51.80175 75.35153 22
## 3 51.30840 73.70618 24
## 4 52.21287 74.32322 23
## 5 50.15725 74.70085 22
## 6 50.15725 74.10256 25
Elas também podem ser visualizadas em gráficos de séries temporais, como ilustram os exemplos a seguir:They can also be visualized in time series plots, as illustrated in the examples below:
As saídas gráficas do Bioma Stats são
objetos oriundos do pacote gráfico ggplot2. Dessa forma, os
gráficos podem ser customizados usando a sintaxe introduzida por Hadley
Wickham no ggplot2. Por exemplo, abaixo usamos a sintaxe do
ggplot2 para mudar a cor dos pontos e remover as grades de
fundo.Graphical outputs from Bioma
Stats are objects from the ggplot2 package. Thus,
plots can be customized using the syntax introduced by Hadley Wickham in
ggplot2. For example, below we use ggplot2
syntax to change point color and remove background grid
lines.
# install.packages("ggplot2")
library(ggplot2)
plot_teste$ai_plot +
geom_point(color = "red") +
theme_minimal() +
theme(panel.grid = element_blank())O Bioma Stats contém um dicionário de classes, indicando seus códigos, níveis hierárquicos, nomes em Português e Inglês, e cores padronizadas pela norma brasileira do IBGE.The Bioma Stats contains a class dictionary listing codes, hierarchical levels, names in Portuguese and English, and colors standardized by the Brazilian IBGE norm.
No exemplo a seguir, o dicionário é carregado a
partir do comando dict_build e, com os códigos processados
em biomastats_metrics, os nomes das classificações usadas
são recuperados.In the example below, the
dictionary is loaded with dict_build and, with the codes
processed in biomastats_metrics, the names of the
classifications used are retrieved.
## [1] "Savanna Formation" "Forest Formation"
O Bioma Stats também apresenta recurso
para visualizar os mapas após a reclassificação. A função
reclass_map processa objetos exportados pela função
biomastats_metrics e, para usá-la, o usuário precisa apenas
informar o objeto exportado (obj = plot_teste, por exemplo)
e o ano de interesse.The Bioma
Stats also provides a feature to visualize maps after
reclassification. The reclass_map function processes
objects exported by biomastats_metrics; to use it, the user
only needs to provide the exported object (obj =
plot_teste, for example) and the year of interest.
Se você deseja:If you would like to:
Entre em contato conosco por e-mailContact us by email
A equipe do CeMECA - UFSCar Lagoa do Sino agradece ao Projeto MapBiomas pela disponibilização das coleções de uso e cobertura da terra. Os dados utilizados neste estudo são provenientes do MapBiomas – Coleção 10 da Série Anual de Mapas de Cobertura e Uso do Solo do Brasil, acessados em https://mapbiomas.org.The CeMECA team at UFSCar Lagoa do Sino thanks the MapBiomas Project for providing land use and land cover collections. Data used in this study come from MapBiomas – Collection 10 of the Annual Series of Land Cover and Land Use Maps of Brazil, accessed at https://mapbiomas.org.
A equipe do CeMECA - UFSCar Lagoa do Sino agradece ao Conselho Nacional de Desenvolvimento Científico e Tecnológico (CNPq) pelo fomento 406540/2023 - 3.The CeMECA team at UFSCar Lagoa do Sino thanks the National Council for Scientific and Technological Development (CNPq) for funding 406540/2023 - 3.
Agradeço a equipe CeMECA pela colaboração no desenvolvimento e teste do Programa Bioma Stats:I thank the CeMECA team for collaboration in developing and testing the Bioma Stats program:
Agradeço aos prof. pesquisadores, membros do Projeto Universal CNPq 406540, que assessoram a equipe de desenvolvimento do Bioma Stats em diversas frentes:I thank the faculty researchers, members of CNPq Universal Project 406540, who advise the Bioma Stats development team in various areas:
O código-fonte deste programa está protegido por direitos autorais e é regido pela Licença GNU Affero General Public License (GNU AGPL) versão 3.0 ou posterior. Qualquer redistribuição ou modificação do código-fonte deve ser realizada de acordo com os termos desta licença.The source code of this program is protected by copyright and is governed by the GNU Affero General Public License (GNU AGPL) version 3.0 or later. Any redistribution or modification of the source code must be carried out in accordance with the terms of this license.
É crucial destacar que a GNU AGPL estabelece a necessidade de que os autores do software sejam devidamente reconhecidos em qualquer redistribuição ou modificação efetuada no código-fonte original. Tal premissa se constitui como um requisito imprescindível para assegurar o respeito aos direitos autorais dos criadores do software, bem como para manter a transparência e a credibilidade do software, objetivos estes que são de grande relevância para toda a comunidade de usuários e desenvolvedores de software livre. Consequentemente, é fundamental observar tal exigência ao utilizar o programa.It is essential to note that the GNU AGPL requires that the software authors be properly acknowledged in any redistribution or modification of the original source code. This is an indispensable requirement to ensure respect for the copyright of the software creators and to maintain transparency and credibility of the software—goals of great relevance to the entire community of free software users and developers. Therefore, it is essential to observe this requirement when using the program.
Ao utilizar este programa, você concorda em cumprir os termos e condições estabelecidos pela Licença GNU Affero General Public License (GNU AGPL) versão 3.0 ou posterior. Para obter mais informações sobre a licença, consulte o arquivo “LICENSE” que acompanha este programa ou acesse o seguinte link: https://www.gnu.org/licenses/agpl-3.0.html.By using this program, you agree to comply with the terms and conditions established by the GNU Affero General Public License (GNU AGPL) version 3.0 or later. For more information about the license, see the “LICENSE” file that accompanies this program or visit: https://www.gnu.org/licenses/agpl-3.0.html.
Durante a preparação deste material e do pacote Bioma Stats, foram utilizadas ferramentas de Inteligência Artificial (IA) como apoio, sob supervisão e revisão da equipe. Especificamente, a IA foi empregada para:During the preparation of this material and of the Bioma Stats package, Artificial Intelligence (AI) tools were used as support, under the team’s supervision and review. Specifically, AI was used for:
Todo o conteúdo gerado com auxílio de IA foi revisado e validado pelos autores, que assumem integral responsabilidade pelas informações apresentadas.All content produced with AI assistance was reviewed and validated by the authors, who take full responsibility for the information presented.