Skip to content

Commit

Permalink
Update plotCorrHist2D 67k and bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
emolinab committed Jan 24, 2025
1 parent 054857c commit e46c522
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 59 deletions.
2 changes: 1 addition & 1 deletion .buildlibrary
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ValidationKey: '8098285'
ValidationKey: '8245920'
AutocreateReadme: yes
AcceptedWarnings:
- 'Warning: package ''.*'' was built under R version'
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ jobs:
[ -f requirements.txt ] && python -m pip install --upgrade pip wheel || true
[ -f requirements.txt ] && pip install -r requirements.txt || true
- name: Run pre-commit checks
shell: bash
run: |
python -m pip install pre-commit
python -m pip freeze --local
pre-commit run --show-diff-on-failure --color=always --all-files
- name: Verify validation key
shell: Rscript {0}
run: lucode2:::validkey(stopIfInvalid = TRUE)
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ repos:
- id: readme-rmd-rendered
- id: use-tidy-description
ci:
autoupdate_schedule: quarterly
autoupdate_schedule: weekly
4 changes: 2 additions & 2 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ cff-version: 1.2.0
message: If you use this software, please cite it using the metadata from this file.
type: software
title: 'luplot: Landuse Plot Library'
version: 4.0.3
date-released: '2025-01-07'
version: 4.1.0
date-released: '2025-01-24'
abstract: Some useful functions to plot data such as a map plot function for MAgPIE
objects.
authors:
Expand Down
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Type: Package
Package: luplot
Title: Landuse Plot Library
Version: 4.0.3
Date: 2025-01-07
Version: 4.1.0
Date: 2025-01-24
Authors@R: c(
person("Benjamin Leon", "Bodirsky", , "bodirsky@pik-potsdam.de", role = c("aut", "cre")),
person("Jan Philipp", "Dietrich", , "dietrich@pik-potsdam.de", role = "aut"),
Expand Down
99 changes: 55 additions & 44 deletions R/plotCorrHist2D.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
#' @param limx limits y axis (if NULL, fitting limits are calculated within the function)
#' @param limy limits x axis (if NULL, fitting limits are calculated within the function)
#' @param bins number of bins in histogram
#' @param folder path in which to save the plots. if "." is used, it is saved
#' @param folder path in which to save the plots. if "." is used, it is saved
#' in the current working directory. If NULL, no plots are saved.
#' @param file name of file
#' @param statFont font size r2-MAE label
Expand All @@ -21,13 +21,14 @@
#' @param ncols number of columns in pdf file where plots are printed
#' @param axisFont Font size of text of axis of the correlation plot
#' @param axisTitleFont Font size of title of axis of the correlation plot
#' @param TitleFontSize Font size of title of correlation plot
#' @param titleFontSize Font size of title of correlation plot
#' @param legendTitleFont Font size of the title of the legend
#' @param legendTextFont Font size of legend
#' @param table Conditional to include table with statistics in the output. TRUE (includes it), FALSE (it doesn't)
#' @param stat Conditional to include R2 and MAE on the fiure. TRUE (includes it), FALSE (it doesn't)
#' @param palette palette selection for heatd maps based on the RColorBrewer library
#' @param tag for multiple items in the second and third dimensions of the magpie object, should the title include "year", "item", "year-item".
#' @param tag for multiple items in the second and third dimensions of the magpie object,
#' should the title include "year", "item", "year-item".
#' @author Edna Molina Bacca
#' @importFrom grDevices colorRampPalette
#' @importFrom ggplot2 ggplot aes_ xlim ylim scale_fill_gradientn coord_fixed geom_abline geom_vline geom_hline
Expand All @@ -42,31 +43,39 @@
#' x <- plotCorrHist2D(x, y, folder = ".")
#' }
#'
plotCorrHist2D <- function(x, y, title = NULL, xlab = "x", ylab = "y", bins = 40, limx=NULL, limy=NULL,
folder = NULL, file = "", breaks = waiver(),nrows=2, ncols=2, axisFont=13,
axisTitleFont=13,TitleFontSize=15,legendTitleFont=12,legendTextFont=10,
statFont=4, table=FALSE, stat=TRUE,palette="RdYlBu",tag=NULL) {
plotCorrHist2D <- function(x, y, title = NULL, xlab = "x", ylab = "y", bins = 40, limx = NULL, limy = NULL,
folder = NULL, file = "", breaks = waiver(), nrows = 2, ncols = 2, axisFont = 13,
axisTitleFont = 13, titleFontSize = 15, legendTitleFont = 12, legendTextFont = 10,
statFont = 4, table = FALSE, stat = TRUE, palette = "RdYlBu", tag = "year-item") {


getNames(x) <- gsub(x = getNames(x), pattern = "\\.", replacement = "_")
getNames(y) <- gsub(x = getNames(y), pattern = "\\.", replacement = "_")

if (length(getCells(x)) == 67420 && length(getCells(y)) == 67420) {
getCells(x) <- gsub(x = getCells(x), pattern = "\\.", replacement = "_")
getCells(y) <- gsub(x = getCells(y), pattern = "\\.", replacement = "_")
}


if (!all(getCells(x) == getCells(y))) stop("Data sets don't have the same regional resolution")
years <- if (!is.null(intersect(getYears(x), getYears(y)))) intersect(getYears(x, as.integer = TRUE),
getYears(y, as.integer = TRUE)) else
stop("No common years between data sets")
stop("No common years between data sets")
names <- if (!is.null(intersect(getNames(x), getNames(y)))) intersect(getNames(x),
getNames(y)) else
stop("No common items between data sets")
stop("No common items between data sets")


plotMagpie <- luplot::as.ggplot(mbind(setNames(x[, years, names], paste0(getNames(x), "_x")),
setNames(y[, years, names],
paste0(getNames(x), "_y"))))[, c("Cell", "Region", "Year", "Data1", "Value")]
plotMagpie <- reshape(plotMagpie, direction = "wide", idvar = c("Cell", "Region", "Year"), timevar = "Data1")
setNames(y[, years, names],
paste0(getNames(x), "_y"))))
cols <- colnames(plotMagpie)[colnames(plotMagpie) != "Scenario"]
plotMagpie <- reshape(plotMagpie[, cols], direction = "wide", idvar = cols[cols != "Data1" & cols != "Value"],
timevar = "Data1")

plots <- list()
corr <- c("Year","Variable", "r2", "MAE", "MPE", "MAPE")
corr <- c("Year", "Variable", "r2", "MAE", "MPE", "MAPE")

rf <- colorRampPalette(rev(brewer.pal(11, palette)))
r <- rf(32) # color palette
Expand Down Expand Up @@ -96,56 +105,58 @@ plotCorrHist2D <- function(x, y, title = NULL, xlab = "x", ylab = "y", bins = 40

r2 <- round(cor(data[, valueX], data[, valueY])^2, 3)
mae <- luplot::qualityMeasure(pd = data[, valueY], od = data[, valueX], measures = "MAE", p_value = FALSE)

relativeError <- (data[, valueY] - data[, valueX]) / data[, valueX]
relativeError[!is.finite(relativeError)] <- NA
relativeError[data[, valueX] < 0.01 * max(data[, valueX])] <- NA
relativeError[data[, valueX] < 0.01 * max(data[, valueX])] <- NA
mpe <- sum(relativeError * 100, na.rm = TRUE) / length(relativeError[is.finite(relativeError)])

absoluteError <- abs((data[, valueY] - data[, valueX]) / data[, valueX])
absoluteError[!is.finite(absoluteError)] <- NA
absoluteError[data[, valueX] < 0.01 * max(data[, valueX])] <- NA
mape <- round(sum(absoluteError * 100, na.rm = TRUE) / length(absoluteError[is.finite(absoluteError)]), 3)

all <- t(c(year,na, r2, mae, mpe, mape))
all <- t(c(year, na, r2, mae, mpe, mape))


corr <- rbind(corr, all)
tag1 <- paste0(na, "-", year)
tagTitle <- if(tag=="year-item") tag1 else if(tag=="year") year else if(tag=="item") na
tagTitle <- if (tag == "year-item") tag1 else if (tag == "year") year else if (tag == "item") na

plots[[tag1]] <- ggplot(data, aes_string(x = valueX, y = valueY)) + theme_bw()
plots[[tag1]] <- plots[[tag1]] + geom_bin2d(bins = bins) + coord_fixed(ratio = 1) +
geom_abline(intercept = 0, slope = 1) + geom_vline(xintercept = 0) + geom_hline(yintercept = 0)
plots[[tag1]] <- plots[[tag1]] + labs(x = xlab, y = ylab, title = paste0(title, " ", "(", tagTitle, ")")) +
scale_fill_gradientn(colours = r, trans = "log", breaks = breaks)
plots[[tag1]] <- plots[[tag1]] + theme(axis.text.x = element_text(color = "grey20", size = axisFont),
axis.title.x = element_text(color = "grey20", size = axisTitleFont),
axis.text.y = element_text(color = "grey20", size = axisFont),
axis.title.y = element_text(color = "grey20", size = axisTitleFont),
plot.title = element_text(size = TitleFontSize, face = "bold"),
legend.text = element_text(size = legendTextFont),
legend.title = element_text(size = legendTitleFont),
legend.background = element_blank())

plots[[tag1]] <- if(stat) plots[[tag1]] + annotate("label", size = statFont, x = labelX, y = labelY,
label = paste0("R2 = ", r2), hjust = 1) else plots[[tag1]]
plots[[tag1]] <- if(stat) plots[[tag1]] + annotate("label", size = statFont, x = labelX, y = labelY2,
label = paste0("MAE = ", mae), hjust = 1) else plots[[tag1]]
plots[[tag1]] <- if (!is.null(limx)) plots[[tag1]] + scale_x_continuous(limits = limx) else plots[[tag1]] + scale_x_continuous(limits = limx1)
plots[[tag1]] <- if (!is.null(limy)) plots[[tag1]] + scale_y_continuous(limits = limy) else plots[[tag1]] + scale_y_continuous(limits = limy1)

axis.title.x = element_text(color = "grey20", size = axisTitleFont),
axis.text.y = element_text(color = "grey20", size = axisFont),
axis.title.y = element_text(color = "grey20", size = axisTitleFont),
plot.title = element_text(size = titleFontSize, face = "bold"),
legend.text = element_text(size = legendTextFont),
legend.title = element_text(size = legendTitleFont),
legend.background = element_blank())

plots[[tag1]] <- if (stat) plots[[tag1]] + annotate("label", size = statFont, x = labelX, y = labelY,
label = paste0("R2 = ", r2), hjust = 1) else plots[[tag1]]
plots[[tag1]] <- if (stat) plots[[tag1]] + annotate("label", size = statFont, x = labelX, y = labelY2,
label = paste0("MAE = ", mae), hjust = 1) else plots[[tag1]]
plots[[tag1]] <- if (!is.null(limx)) plots[[tag1]] + scale_x_continuous(limits = limx) else plots[[tag1]] +
scale_x_continuous(limits = limx1)
plots[[tag1]] <- if (!is.null(limy)) plots[[tag1]] + scale_y_continuous(limits = limy) else plots[[tag1]] +
scale_y_continuous(limits = limy1)

}
}
if (!is.null(folder)) {
if (folder != "." && !dir.exists(folder)) dir.create(folder)
if(is.null(file)) stop("Please, write a file name")
ml<-gridExtra::marrangeGrob(plots, nrow = 2, ncol = 2)
ggsave(paste0(folder,file,".pdf"), ml)
write.csv2(corr,paste0(folder, file, "_stats.csv"))
}

out <- if (table) list(plots,corr) else plots

if (!is.null(folder)) {
if (folder != "." && !dir.exists(folder)) dir.create(folder)
if (is.null(file)) stop("Please, write a file name")
ml <- gridExtra::marrangeGrob(plots, nrow = nrows, ncol = ncols)
ggsave(paste0(folder, file, ".pdf"), ml)
write.csv2(corr, paste0(folder, file, "_stats.csv"))
}

out <- if (table) list(plots, corr) else plots
return(out)
}
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Landuse Plot Library

R package **luplot**, version **4.0.3**
R package **luplot**, version **4.1.0**

[![CRAN status](https://www.r-pkg.org/badges/version/luplot)](https://cran.r-project.org/package=luplot) [![R build status](https://github.com/pik-piam/luplot/workflows/check/badge.svg)](https://github.com/pik-piam/luplot/actions) [![codecov](https://codecov.io/gh/pik-piam/luplot/branch/master/graph/badge.svg)](https://app.codecov.io/gh/pik-piam/luplot) [![r-universe](https://pik-piam.r-universe.dev/badges/luplot)](https://pik-piam.r-universe.dev/builds)

Expand Down Expand Up @@ -39,15 +39,17 @@ In case of questions / problems please contact Benjamin Bodirsky <bodirsky@pik-p

To cite package **luplot** in publications use:

Bodirsky B, Dietrich J, Krause M, Stevanovic M, Humpenoeder F, Weindl I, Baumstark L, Klein D, Rolinski S, Wang X, Chen D, Sauer P (2025). "luplot: Landuse Plot Library - Version 4.0.3."
Bodirsky B, Dietrich J, Krause M, Stevanovic M, Humpenoeder F, Weindl I, Baumstark L, Klein D, Rolinski S, Wang X, Chen D, Sauer P (2025). "luplot: Landuse Plot Library." Version: 4.1.0, <https://github.com/pik-piam/luplot>.

A BibTeX entry for LaTeX users is

```latex
@Misc{,
title = {luplot: Landuse Plot Library - Version 4.0.3},
title = {luplot: Landuse Plot Library},
author = {Benjamin Leon Bodirsky and Jan Philipp Dietrich and Michael Krause and Miodrag Stevanovic and Florian Humpenoeder and Isabelle Weindl and Lavinia Baumstark and David Klein and Susanne Rolinski and Xiaoxi Wang and David Chen and Pascal Sauer},
date = {2025-01-07},
date = {2025-01-24},
year = {2025},
url = {https://github.com/pik-piam/luplot},
note = {Version: 4.1.0},
}
```
11 changes: 6 additions & 5 deletions man/plotCorrHist2D.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e46c522

Please sign in to comment.