| Title: | ggplot layers |
|---|---|
| Description: | What the package does (one paragraph). |
| Authors: | Dongdong Kong [aut, cre] (ORCID: <https://orcid.org/0000-0003-1836-8172>) |
| Maintainer: | Dongdong Kong <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.1.3 |
| Built: | 2026-05-28 06:39:32 UTC |
| Source: | https://github.com/rpkgs/gg.layers |
add_colorbar
add_colorbar( p, g, width = NULL, height = NULL, title = NULL, space = "right", legend.title = element_text(hjust = 0, vjust = 0, size = 14, family = "Times") )add_colorbar( p, g, width = NULL, height = NULL, title = NULL, space = "right", legend.title = element_text(hjust = 0, vjust = 0, size = 14, family = "Times") )
p |
a ggplot object |
g |
a grob object, colorbar |
width, height
|
width and height of the colorbar |
title |
all title elements: plot, axes, legends ( |
space |
one of |
legend.title |
title of legend ( |
add grob to a plot
add_grob(p, ..., ggplot = TRUE)add_grob(p, ..., ggplot = TRUE)
p |
ggplot object |
... |
grob objects |
ggplot |
logical, if TRUE, return a ggplot object |
library(ggplot2) library(grid) p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl) g1 <- textGrob("hello", x = 0.98, y = 0.1, hjust = 1, vjust = 0, gp = gpar(fontfamily = "Times")) g2 <- element_grob_text(element_text(family = "Times", hjust = 1, vjust = 0, size = 12), label = "Hello world", x = 0.98, y = 0.2) add_grob(p, g1, g2) add_grob(p, g1) %>% add_grob(g2)library(ggplot2) library(grid) p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl) g1 <- textGrob("hello", x = 0.98, y = 0.1, hjust = 1, vjust = 0, gp = gpar(fontfamily = "Times")) g2 <- element_grob_text(element_text(family = "Times", hjust = 1, vjust = 0, size = 12), label = "Hello world", x = 0.98, y = 0.2) add_grob(p, g1, g2) add_grob(p, g1) %>% add_grob(g2)
colourbar_triangle
colourbar_triangle(...)colourbar_triangle(...)
... |
parameters passed to ggplot2::guide_colourbar |
library(ggplot2) g <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = drat)) g + scale_colour_viridis_c( limits = c(3, 5), oob = scales::oob_squish, guide = colourbar_triangle() )library(ggplot2) g <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = drat)) g + scale_colour_viridis_c( limits = c(3, 5), oob = scales::oob_squish, guide = colourbar_triangle() )
draw horizontal and vertical polygons
draw_polygon( vals, x = NULL, type = "horizontal", length.out = 10000, col.regions = c("blue", "red"), alpha = 0.6, zlim = c(-Inf, Inf), ... )draw_polygon( vals, x = NULL, type = "horizontal", length.out = 10000, col.regions = c("blue", "red"), alpha = 0.6, zlim = c(-Inf, Inf), ... )
vals |
numeric vector |
x |
The corresponding x position of |
type |
one of "horizontal" or "vertical" |
length.out |
the length of interpolated |
col.regions |
A vector of colors, or a function to produce a vecor of colors, to
be used if |
alpha |
the alpha of polygon's fill color |
zlim |
limits of |
... |
Extra parameters. |
set.seed(1) y <- rnorm(10) x <- seq_along(y)set.seed(1) y <- rnorm(10) x <- seq_along(y)
geom_annotation
geom_annotation( mapping = NULL, data = NULL, stat = "identity", position = "identity", xmin = 0, xmax = 0.5, ymin = 0, ymax = 0.5, just = c(0, 0), ..., na.rm = FALSE, show.legend = NA, inherit.aes = FALSE )geom_annotation( mapping = NULL, data = NULL, stat = "identity", position = "identity", xmin = 0, xmax = 0.5, ymin = 0, ymax = 0.5, just = c(0, 0), ..., na.rm = FALSE, show.legend = NA, inherit.aes = FALSE )
mapping |
Set of aesthetic mappings created by |
data |
A tibble with the column of |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
xmin, xmax
|
x location (in data coordinates) giving horizontal location of raster |
ymin, ymax
|
y location (in data coordinates) giving vertical location of raster |
just |
A string or numeric
vector specifying the justification of the viewport
relative to its (x, y) location. If there are two values, the first
value specifies horizontal justification and the second value specifies
vertical justification. Possible string values are: |
... |
Other arguments passed on to
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
## make plot library(ggplot2) d <- data.frame(x = 1:3, y = 1:3, varname = c("T_min", "T_max", "T_avg")) p = ggplot(d, aes(x, y)) + geom_point() + geom_richtext(aes(label = varname), x = 2, y = 2) + facet_wrap(~varname, labeller = label_mk) + theme( strip.text = element_markdown(face = "bold", margin = margin(t = 1, b = 0)) ) ## make legend brks = 1:5 %>% c(-Inf, ., Inf) nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) g = make_colorbar(brks, col = cols, space = "right") d_lgd = tibble(varname = d$varname, grob = rep(list(g), 3)) ## add legend to each panel p2 = p + geom_annotation(data = d_lgd, aes(grob = grob), xmin = 0.8, xmax = 1, ymax = 1) p2## make plot library(ggplot2) d <- data.frame(x = 1:3, y = 1:3, varname = c("T_min", "T_max", "T_avg")) p = ggplot(d, aes(x, y)) + geom_point() + geom_richtext(aes(label = varname), x = 2, y = 2) + facet_wrap(~varname, labeller = label_mk) + theme( strip.text = element_markdown(face = "bold", margin = margin(t = 1, b = 0)) ) ## make legend brks = 1:5 %>% c(-Inf, ., Inf) nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) g = make_colorbar(brks, col = cols, space = "right") d_lgd = tibble(varname = d$varname, grob = rep(list(g), 3)) ## add legend to each panel p2 = p + geom_annotation(data = d_lgd, aes(grob = grob), xmin = 0.8, xmax = 1, ymax = 1) p2
geom_annotation
geom_annotation_func( mapping = NULL, data = NULL, plot.fun = NULL, ..., x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0) )geom_annotation_func( mapping = NULL, data = NULL, plot.fun = NULL, ..., x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0) )
mapping |
Set of aesthetic mappings created by |
data |
A tibble with the column of |
plot.fun |
function to plot, |
... |
other parameters to |
x |
A numeric vector or unit object specifying x-location. |
y |
A numeric vector or unit object specifying y-location. |
width |
A numeric vector or unit object specifying width. |
height |
A numeric vector or unit object specifying height. |
just |
A string or numeric
vector specifying the justification of the viewport
relative to its (x, y) location. If there are two values, the first
value specifies horizontal justification and the second value specifies
vertical justification. Possible string values are: |
## prepare data library(gg.layers) library(ggplot2) library(rcolors) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) %>% as_tibble() n <- nrow(d_mask) * 2 dat <- rbind(cbind(type = "a", d_mask), cbind(type = "b", d_mask)) %>% mutate(val = rnorm(n)) brks <- seq(0.9, 1, 0.025) nbrk <- length(brks) - 1 cols <- get_color(rcolors$amwg256, nbrk) ## option1 # the part of not significant ggplot(data = dat, aes(x, y)) + geom_raster(aes(fill = perc)) + layer_barchart(aes(z = val), width = unit(0.3, "npc"), height = unit(0.3, "npc"), brks = brks, cols = cols ) + facet_wrap(~type) ## option2 func <- function(data, ...) { add_barchart(data$z, brks, cols, ...) } ggplot(data = dat, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_annotation_func(aes(z = val), plot.fun = func) + facet_wrap(~type)## prepare data library(gg.layers) library(ggplot2) library(rcolors) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) %>% as_tibble() n <- nrow(d_mask) * 2 dat <- rbind(cbind(type = "a", d_mask), cbind(type = "b", d_mask)) %>% mutate(val = rnorm(n)) brks <- seq(0.9, 1, 0.025) nbrk <- length(brks) - 1 cols <- get_color(rcolors$amwg256, nbrk) ## option1 # the part of not significant ggplot(data = dat, aes(x, y)) + geom_raster(aes(fill = perc)) + layer_barchart(aes(z = val), width = unit(0.3, "npc"), height = unit(0.3, "npc"), brks = brks, cols = cols ) + facet_wrap(~type) ## option2 func <- function(data, ...) { add_barchart(data$z, brks, cols, ...) } ggplot(data = dat, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_annotation_func(aes(z = val), plot.fun = func) + facet_wrap(~type)
The boxplot compactly displays the distribution of a continuous variable. It visualises five summary statistics (the median, two hinges and two whiskers), and all "outlying" points individually.
geom_boxplot2( mapping = NULL, data = NULL, stat = "boxplot", position = "dodge2", ..., outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, show.errorbar = TRUE, width.errorbar = 0.7, notch = FALSE, notchwidth = 0.5, varwidth = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_boxplot2( mapping = NULL, data = NULL, stat = "boxplot", position = "dodge2", ..., outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, show.errorbar = TRUE, width.errorbar = 0.7, notch = FALSE, notchwidth = 0.5, varwidth = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
the statistical transformation to use on the data for this layer |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
outlier.colour, outlier.color, outlier.fill, outlier.shape, outlier.size, outlier.stroke, outlier.alpha
|
Default aesthetics for outliers. Set to |
show.errorbar |
whether to show errorbar (default TRUE) |
width.errorbar |
the width of errorbar (default 0.7) |
notch |
If |
notchwidth |
For a notched box plot, width of the notch relative to
the body (defaults to |
varwidth |
If |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
geom_boxplot() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:
| • | x or y |
|
| • | lower or xlower |
|
| • | upper or xupper |
|
| • | middle or xmiddle |
|
| • | ymin or xmin |
|
| • | ymax or xmax |
|
| • | alpha |
→ NA |
| • | colour |
→ via theme() |
| • | fill |
→ via theme() |
| • | group |
→ inferred |
| • | linetype |
→ via theme() |
| • | linewidth |
→ via theme() |
| • | shape |
→ via theme() |
| • | size |
→ via theme() |
| • | weight |
→ 1 |
| • | width |
→ 0.9
|
Learn more about setting these aesthetics in vignette("ggplot2-specs").
The lower and upper hinges correspond to the first and third quartiles
(the 25th and 75th percentiles). This differs slightly from the method used
by the boxplot() function, and may be apparent with small samples.
See boxplot.stats() for more information on how hinge
positions are calculated for boxplot().
The upper whisker extends from the hinge to the largest value no further than 1.5 * IQR from the hinge (where IQR is the inter-quartile range, or distance between the first and third quartiles). The lower whisker extends from the hinge to the smallest value at most 1.5 * IQR of the hinge. Data beyond the end of the whiskers are called "outlying" points and are plotted individually.
In a notched box plot, the notches extend 1.58 * IQR / sqrt(n).
This gives a roughly 95% confidence interval for comparing medians.
See McGill et al. (1978) for more details.
McGill, R., Tukey, J. W. and Larsen, W. A. (1978) Variations of box plots. The American Statistician 32, 12-16.
ggplot2::geom_quantile() for continuous x,
ggplot2::geom_violin() for a richer display of the distribution, and
ggplot2::geom_jitter() for a useful technique for small data.
library(ggplot2) p <- ggplot(mpg, aes(class, hwy)) p + geom_boxplot2() p + geom_boxplot2(width.errorbar = 0.5) p + geom_boxplot2(width = 0.5) # Orientation follows the discrete axis # ggplot(mpg, aes(hwy, class)) + geom_boxplot2() p + geom_boxplot2(notch = TRUE) p + geom_boxplot2(varwidth = TRUE) p + geom_boxplot2(fill = "white", colour = "#3366FF") # By default, outlier points match the colour of the box. Use # outlier.colour to override p + geom_boxplot2(outlier.colour = "red", outlier.shape = 1) # Remove outliers when overlaying boxplot with original data points p + geom_boxplot2(outlier.shape = NA) + geom_jitter(width = 0.2) # Boxplots are automatically dodged when any aesthetic is a factor p + geom_boxplot2(aes(colour = drv)) # You can also use boxplots with continuous x, as long as you supply # a grouping variable. cut_width is particularly useful # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2() # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2(aes(group = cut_width(carat, 0.25))) # Adjust the transparency of outliers using outlier.alpha # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1) # It's possible to draw a boxplot with your own computations if you # use stat = "identity": y <- rnorm(100) df <- data.frame( x = 1, y0 = min(y), y25 = quantile(y, 0.25), y50 = median(y), y75 = quantile(y, 0.75), y100 = max(y) ) ggplot(df, aes(x)) + geom_boxplot2( aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100), stat = "identity" )library(ggplot2) p <- ggplot(mpg, aes(class, hwy)) p + geom_boxplot2() p + geom_boxplot2(width.errorbar = 0.5) p + geom_boxplot2(width = 0.5) # Orientation follows the discrete axis # ggplot(mpg, aes(hwy, class)) + geom_boxplot2() p + geom_boxplot2(notch = TRUE) p + geom_boxplot2(varwidth = TRUE) p + geom_boxplot2(fill = "white", colour = "#3366FF") # By default, outlier points match the colour of the box. Use # outlier.colour to override p + geom_boxplot2(outlier.colour = "red", outlier.shape = 1) # Remove outliers when overlaying boxplot with original data points p + geom_boxplot2(outlier.shape = NA) + geom_jitter(width = 0.2) # Boxplots are automatically dodged when any aesthetic is a factor p + geom_boxplot2(aes(colour = drv)) # You can also use boxplots with continuous x, as long as you supply # a grouping variable. cut_width is particularly useful # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2() # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2(aes(group = cut_width(carat, 0.25))) # Adjust the transparency of outliers using outlier.alpha # ggplot(diamonds, aes(carat, price)) + # geom_boxplot2(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1) # It's possible to draw a boxplot with your own computations if you # use stat = "identity": y <- rnorm(100) df <- data.frame( x = 1, y0 = min(y), y25 = quantile(y, 0.25), y50 = median(y), y75 = quantile(y, 0.75), y100 = max(y) ) ggplot(df, aes(x)) + geom_boxplot2( aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100), stat = "identity" )
xmin, xmax
ymin, ymax: optional
geom_hspan( mapping = NULL, data = NULL, stat = "hspan", position = "identity", ..., ymin = -Inf, ymax = Inf, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_hspan( mapping = NULL, data = NULL, stat = "hspan", position = "identity", ..., ymin = -Inf, ymax = Inf, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(ggplot2) library(data.table) d = data.table(x = 1:10, y = 1:10) d_span = data.table(xmin = c(1, 4), xmax = c(3, 5), group = 1:2) ggplot(d, aes(x, y)) + geom_point() + geom_hspan(data = d_span, aes(x = NULL, y = NULL, xmin = xmin, xmax = xmax, group = group), alpha = 0.2, fill = "yellow")library(ggplot2) library(data.table) d = data.table(x = 1:10, y = 1:10) d_span = data.table(xmin = c(1, 4), xmax = c(3, 5), group = 1:2) ggplot(d, aes(x, y)) + geom_point() + geom_hspan(data = d_span, aes(x = NULL, y = NULL, xmin = xmin, xmax = xmax, group = group), alpha = 0.2, fill = "yellow")
geom_latFreq
geom_latFreq( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., options = list(), bbox = c(185, 240, -60, 90), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_latFreq( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., options = list(), bbox = c(185, 240, -60, 90), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
options |
parameters of |
bbox |
bounding box of the plot, in the form of |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(ggplot2) # the lattice version: https://github.com/CUG-hydro/Liu2021-JGRA-ET_trends_attribution # f <- "data-raw/AridityIndex_MSWEP-prcp_div_GLEAM-Ep_1980-2020.tif" # r <- terra::rast(f) # d <- as.data.table(r, xy = TRUE) |> set_names(c("x", "y", "z")) d = AridityIndex # make_latFreq(d$y, d$z, debug = TRUE, zlim = c(-2, 2), is_spatial = TRUE) # brks <- c(-Inf, 0.05, 0.2, 0.5, 0.65, Inf) brks <- c(-Inf, 0.05, 0.2, 0.5, 0.65, 1:5, 20, Inf) nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) |> rev() p = ggplot(d, aes(x, y, z = z)) + geom_raster_filled(breaks = brks) + geom_latFreq(options = list(is_spatial = TRUE, zlim = c(-1, 1)*10), bbox = c(190, 240, -60, 90)) + coord_cartesian(xlim = c(-180, 240), ylim = c(-60, 90), expand = FALSE, clip = "on") + scale_x_continuous(limits = c(-180, 240), breaks = seq(-180, 180, 60)) + scale_fill_manual(values =cols) + labs(x = NULL, y = NULL) plibrary(ggplot2) # the lattice version: https://github.com/CUG-hydro/Liu2021-JGRA-ET_trends_attribution # f <- "data-raw/AridityIndex_MSWEP-prcp_div_GLEAM-Ep_1980-2020.tif" # r <- terra::rast(f) # d <- as.data.table(r, xy = TRUE) |> set_names(c("x", "y", "z")) d = AridityIndex # make_latFreq(d$y, d$z, debug = TRUE, zlim = c(-2, 2), is_spatial = TRUE) # brks <- c(-Inf, 0.05, 0.2, 0.5, 0.65, Inf) brks <- c(-Inf, 0.05, 0.2, 0.5, 0.65, 1:5, 20, Inf) nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) |> rev() p = ggplot(d, aes(x, y, z = z)) + geom_raster_filled(breaks = brks) + geom_latFreq(options = list(is_spatial = TRUE, zlim = c(-1, 1)*10), bbox = c(190, 240, -60, 90)) + coord_cartesian(xlim = c(-180, 240), ylim = c(-60, 90), expand = FALSE, clip = "on") + scale_x_continuous(limits = c(-180, 240), breaks = seq(-180, 180, 60)) + scale_fill_manual(values =cols) + labs(x = NULL, y = NULL) p
geom_mk
geom_mk( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., fun_slope = slope_mk, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_mk( mapping = NULL, data = NULL, geom = "abline", position = "identity", fun_slope = slope_mk, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) stat_spike( mapping = NULL, data = NULL, geom = "point", position = "identity", halfwin = 3, sd.times = 3, trs = NA, verbose = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )geom_mk( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., fun_slope = slope_mk, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_mk( mapping = NULL, data = NULL, geom = "abline", position = "identity", fun_slope = slope_mk, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) stat_spike( mapping = NULL, data = NULL, geom = "point", position = "identity", halfwin = 3, sd.times = 3, trs = NA, verbose = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
fun_slope |
function to calculate slope, default |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
No return. This function is used to calculate data for gglot2 geom_*,
just like ggplot2::stat_smooth().
No return. This function is used to calculate data for gglot2 geom_*,
just like ggplot2::stat_smooth().
library(ggplot2) library(rtrend) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + geom_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) library(ggplot2) library(rtrend) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + geom_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2)library(ggplot2) library(rtrend) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + geom_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) library(ggplot2) library(rtrend) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2) ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + geom_mk(linewidth = 1, fun_slope = slope_mk) + geom_smooth(method = "lm", se = FALSE, linetype = 2)
geom_movmean
geom_movmean( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., halfwin = 3, show.diff = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_movmean( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., halfwin = 3, show.diff = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
halfwin |
halfwin of movmean, |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(data.table) library(ggplot2) data("GPP_US_MMS") dat = melt(GPP_US_MMS[, .(date, SM, GPP)], "date") ggplot(dat, aes(date, value)) + geom_line() + geom_movmean(halfwin = 5, linewidth = 1, alpha = 0.7, color = "pink") + # geom_movmean(halfwin = 5, show.diff=TRUE, linewidth = 0.2, alpha = 0.7, color = "red") + geom_spike(halfwin = 2, sd.times = 6, color = "red", verbose = TRUE) + # geom_spike(halfwin = 5, trs = 3, color = "blue") + facet_wrap(~variable, scales = "free_y")library(data.table) library(ggplot2) data("GPP_US_MMS") dat = melt(GPP_US_MMS[, .(date, SM, GPP)], "date") ggplot(dat, aes(date, value)) + geom_line() + geom_movmean(halfwin = 5, linewidth = 1, alpha = 0.7, color = "pink") + # geom_movmean(halfwin = 5, show.diff=TRUE, linewidth = 0.2, alpha = 0.7, color = "red") + geom_spike(halfwin = 2, sd.times = 6, color = "red", verbose = TRUE) + # geom_spike(halfwin = 5, trs = 3, color = "blue") + facet_wrap(~variable, scales = "free_y")
Draw precipitation bar on the top of the panel
geom_prcpRunoff( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, prcp.ratio = 0.5, params_prcp = list(), prcp.coef = 1, qmax = NULL, sec.axis = NULL, sec.name = "Precipitation (mm)" )geom_prcpRunoff( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, prcp.ratio = 0.5, params_prcp = list(), prcp.coef = 1, qmax = NULL, sec.axis = NULL, sec.name = "Precipitation (mm)" )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
linejoin |
Line join style (round, mitre, bevel). |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
prcp.ratio |
the ratio of precipitation to |
params_prcp |
|
prcp.coef |
coefficient of precipitation, |
qmax |
maximum of streamflow, used to calculate |
sec.axis |
secondary axis for precipitation, returned by
|
sec.name |
name of secondary axis |
x: date or continuous variable
y: runoff
prcp: precipitation
Xie YuXuan and Dongdong Kong
library(ggplot2) col_prcp = "blue" #"#3e89be" col_runoff = "black" # "darkorange" my_theme <- theme_dual_axis(col_runoff, col_prcp) + theme( legend.position.inside = c(0, 1), legend.justification = c(0, 1), legend.background = element_blank(), legend.key = element_blank(), # axis.ticks = element_blank(), axis.text = element_text(color = "black"), axis.text.x = element_text(angle = 60, hjust = 1), strip.background = element_blank(), strip.text = element_text(face = "bold", hjust = 0) ) ## Visualization --------------------------------------------------------------- dat <- runoff_data qmax <- max(dat$Q) * 1.1 prcp.coef <- guess_prcp_coef(qmax, dat$prcp, ratio = 0.5) # prcp.coef = qmax / pmax * ratio ggplot(dat, aes(x = time, Q)) + # theme_test() + geom_line() + geom_prcpRunoff( aes(prcp = prcp, color = flood_type), params_prcp = list(color = col_prcp, fill = col_prcp), prcp.coef = prcp.coef, qmax = qmax, color = col_runoff, linewidth = 0.5 ) + facet_wrap(~flood_type, scales = "free") + # scale_y_precipitation(sec.name = "Precipitation (mm)", coef = set_coef) + scale_x_datetime(date_labels = "%m/%d") + my_theme + labs(x = "Date", y = expression("Streamflow (m"^"3" * "/s)"))library(ggplot2) col_prcp = "blue" #"#3e89be" col_runoff = "black" # "darkorange" my_theme <- theme_dual_axis(col_runoff, col_prcp) + theme( legend.position.inside = c(0, 1), legend.justification = c(0, 1), legend.background = element_blank(), legend.key = element_blank(), # axis.ticks = element_blank(), axis.text = element_text(color = "black"), axis.text.x = element_text(angle = 60, hjust = 1), strip.background = element_blank(), strip.text = element_text(face = "bold", hjust = 0) ) ## Visualization --------------------------------------------------------------- dat <- runoff_data qmax <- max(dat$Q) * 1.1 prcp.coef <- guess_prcp_coef(qmax, dat$prcp, ratio = 0.5) # prcp.coef = qmax / pmax * ratio ggplot(dat, aes(x = time, Q)) + # theme_test() + geom_line() + geom_prcpRunoff( aes(prcp = prcp, color = flood_type), params_prcp = list(color = col_prcp, fill = col_prcp), prcp.coef = prcp.coef, qmax = qmax, color = col_runoff, linewidth = 0.5 ) + facet_wrap(~flood_type, scales = "free") + # scale_y_precipitation(sec.name = "Precipitation (mm)", coef = set_coef) + scale_x_datetime(date_labels = "%m/%d") + my_theme + labs(x = "Date", y = expression("Streamflow (m"^"3" * "/s)"))
geom_raster_filled
geom_raster_filled( mapping = NULL, data = NULL, stat = "raster_filled", position = "identity", ..., breaks = NULL, hjust = 0.5, vjust = 0.5, interpolate = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_raster_filled( mapping = NULL, data = NULL, geom = "raster", position = "identity", ..., breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_raster_filled( mapping = NULL, data = NULL, stat = "raster_filled", position = "identity", ..., breaks = NULL, hjust = 0.5, vjust = 0.5, interpolate = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_raster_filled( mapping = NULL, data = NULL, geom = "raster", position = "identity", ..., breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
breaks |
One of:
Overrides |
hjust, vjust
|
horizontal and vertical justification of the grob. Each justification value should be a number between 0 and 1. Defaults to 0.5 for both, centering each pixel over its data location. |
interpolate |
If |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
geom |
The geometric object to use to display the data for this layer.
When using a
|
Text with Normalised Parent Coordinates
geom_richtext_npc( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., nudge_x = 0, nudge_y = 0, label.padding = unit(c(0.25, 0.25, 0.25, 0.25), "lines"), label.margin = unit(c(0, 0, 0, 0), "lines"), label.r = unit(0.15, "lines"), na.rm = FALSE, show.legend = FALSE, inherit.aes = FALSE ) annotate_richtext_npc(x, y, label, size = 5, family = "", ...) annotate_richlabel_npc( x, y, label, size = 5, family = "", fill = "white", label.color = "black", ... ) annotate_label_npc( x, y, label, size = 5, family = "", fill = "white", label.color = "black", ... )geom_richtext_npc( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., nudge_x = 0, nudge_y = 0, label.padding = unit(c(0.25, 0.25, 0.25, 0.25), "lines"), label.margin = unit(c(0, 0, 0, 0), "lines"), label.r = unit(0.15, "lines"), na.rm = FALSE, show.legend = FALSE, inherit.aes = FALSE ) annotate_richtext_npc(x, y, label, size = 5, family = "", ...) annotate_richlabel_npc( x, y, label, size = 5, family = "", fill = "white", label.color = "black", ... ) annotate_label_npc( x, y, label, size = 5, family = "", fill = "white", label.color = "black", ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer, as a string. |
position |
Position adjustment, either as a string, or the result of
a call to a position adjustment function. Cannot be jointy specified with
|
... |
Other arguments passed on to |
nudge_x |
Horizontal and vertical adjustment to nudge labels by.
Useful for offsetting text from points, particularly on discrete scales.
Cannot be jointly specified with |
nudge_y |
Horizontal and vertical adjustment to nudge labels by.
Useful for offsetting text from points, particularly on discrete scales.
Cannot be jointly specified with |
label.padding |
Amount of padding around label. Defaults to 0.25 lines. |
label.margin |
Unit vector of length four specifying the margin outside the text label. |
label.r |
Radius of rounded corners. Defaults to 0.15 lines. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
x |
A numeric vector or unit object specifying x-values. |
y |
A numeric vector or unit object specifying y-values. |
label |
A character or expression vector. Other
objects are coerced by |
geom_richtext() understands the following aesthetics (required
aesthetics are in bold; select aesthetics are annotated):
x
y
label
alpha
angle
colour Default color of label text and label outline.
family
fontface
fill Default fill color of label background.
group
hjust
label.colour Color of label outline. Overrides colour.
label.size Width of label outline.
lineheight
size Default font size of label text.
text.colour Color of label text. Overrides colour.
vjust
ggtext::geom_richtext(), geom_richtext2()
library(ggplot2) ## first example labels <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1" # "gC \n mm/d" ) x = 0.2 y = seq_along(labels)/10 ggplot() + annotate_richtext_npc(x, y, labels, size = 5) ggplot() + annotate_richlabel_npc(x, y, labels, size = 5, label.color = "red") # Another option d = data.frame(x = 0.2, y = seq_along(labels)/10, label = labels) ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label)) # remove fill and label.color ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label), fill = "white", label.color = "red") ## second example d$label <- c( "Some text **in bold.**", "Linebreaks<br>Linebreaks<br>Linebreaks", "*x*<sup>2</sup> + 5*x* + *C*<sub>*i*</sub>", "Some <span style='color:blue'>blue text **in bold.**</span><br>And *italics text.*<br> And some <span style='font-size:18pt; color:black'>large</span> text." ) ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label)) ## test for `str_mk` library(magrittr) indexes_lev = c("DOY_first", "DOY_last", "HWD", "HWI", "HWS_mean", "HWS_sum", "HWA_avg", "HWA_max", "HWA_sum") labels = indexes_lev %>% str_mk() #%>% label_tag(expression = F) d = data.frame(x = 0.5, y = 0.5, label = labels) ggplot(d) + facet_wrap(~label) + theme(strip.text.x = element_textbox(face = "bold")) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label))library(ggplot2) ## first example labels <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1" # "gC \n mm/d" ) x = 0.2 y = seq_along(labels)/10 ggplot() + annotate_richtext_npc(x, y, labels, size = 5) ggplot() + annotate_richlabel_npc(x, y, labels, size = 5, label.color = "red") # Another option d = data.frame(x = 0.2, y = seq_along(labels)/10, label = labels) ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label)) # remove fill and label.color ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label), fill = "white", label.color = "red") ## second example d$label <- c( "Some text **in bold.**", "Linebreaks<br>Linebreaks<br>Linebreaks", "*x*<sup>2</sup> + 5*x* + *C*<sub>*i*</sub>", "Some <span style='color:blue'>blue text **in bold.**</span><br>And *italics text.*<br> And some <span style='font-size:18pt; color:black'>large</span> text." ) ggplot(d, aes(npcx = x, npcy = y)) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label)) ## test for `str_mk` library(magrittr) indexes_lev = c("DOY_first", "DOY_last", "HWD", "HWI", "HWS_mean", "HWS_sum", "HWA_avg", "HWA_max", "HWA_sum") labels = indexes_lev %>% str_mk() #%>% label_tag(expression = F) d = data.frame(x = 0.5, y = 0.5, label = labels) ggplot(d) + facet_wrap(~label) + theme(strip.text.x = element_textbox(face = "bold")) + geom_richtext_npc(aes(npcx = x, npcy = y, label = label))
This geom draws text labels similar to ggplot2::geom_label(), but formatted
using basic markdown/html. Parameter and aesthetic names follow the conventions
of ggplot2::geom_label(), and therefore the appearance of the frame around
the label is controlled with label.colour, label.padding, label.margin,
label.size, label.r, even though the same parameters are called box.colour,
box.padding, box.margin, box.size, and box.r in ggtext::geom_textbox(). Most
styling parameters can be used as aesthetics and can be applied separately to
each text label drawn. The exception is styling parameters that are specified
as grid units (e.g., label.padding or label.r), which can only be specified
for all text labels at once. See examples for details.
geom_richtext2( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., nudge_x = 0, nudge_y = 0, label.padding = unit(c(0.25, 0.25, 0.25, 0.25), "lines"), label.margin = unit(c(0, 0, 0, 0), "lines"), label.r = unit(0.15, "lines"), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_richtext2( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., nudge_x = 0, nudge_y = 0, label.padding = unit(c(0.25, 0.25, 0.25, 0.25), "lines"), label.margin = unit(c(0, 0, 0, 0), "lines"), label.r = unit(0.15, "lines"), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer, as a string. |
position |
Position adjustment, either as a string, or the result of
a call to a position adjustment function. Cannot be jointy specified with
|
... |
Other arguments passed on to |
nudge_x |
Horizontal and vertical adjustment to nudge labels by.
Useful for offsetting text from points, particularly on discrete scales.
Cannot be jointly specified with |
nudge_y |
Horizontal and vertical adjustment to nudge labels by.
Useful for offsetting text from points, particularly on discrete scales.
Cannot be jointly specified with |
label.padding |
Amount of padding around label. Defaults to 0.25 lines. |
label.margin |
Unit vector of length four specifying the margin outside the text label. |
label.r |
Radius of rounded corners. Defaults to 0.15 lines. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
A ggplot2 layer that can be added to a plot created with
ggplot2::ggplot().
geom_richtext() understands the following aesthetics (required
aesthetics are in bold; select aesthetics are annotated):
x
y
label
alpha
angle
colour Default color of label text and label outline.
family
fontface
fill Default fill color of label background.
group
hjust
label.colour Color of label outline. Overrides colour.
label.size Width of label outline.
lineheight
size Default font size of label text.
text.colour Color of label text. Overrides colour.
vjust
ggtext::geom_textbox(), ggtext::element_markdown()
library(ggplot2) labels1 = c( "Some text **in bold.**", "Linebreaks<br>Linebreaks<br>Linebreaks", "*x*<sup>2</sup> + 5*x* + *C*<sub>*i*</sub>", "Some <span style='color:blue'>blue text **in bold.**</span><br>And *italics text.*<br> And some <span style='font-size:18pt; color:black'>large</span> text." ) labels2 <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1" # "gC \n mm/d" ) df <- data.frame( x = c(.2, .1, .5, .9), y = c(.8, .4, .1, .5), hjust = c(0.5, 0, 0, 1), vjust = c(0.5, 1, 0, 0.5), angle = c(0, 0, 45, -45), color = c("black", "blue", "black", "red"), fill = c("cornsilk", "white", "lightblue1", "white") ) fun <- function(labels) { df$label = labels ggplot(df, aes(x, y, label = label, angle = angle, color = color, hjust = hjust, vjust = vjust)) + geom_richtext2( fill = NA, label.color = NA, # remove background and outline label.padding = grid::unit(rep(0, 4), "pt") # remove padding ) + geom_point(color = "black", size = 2) + scale_color_identity() + xlim(0, 1) + ylim(0, 1) } fun(labels1) fun(labels2) # labels without frame or background are also possiblelibrary(ggplot2) labels1 = c( "Some text **in bold.**", "Linebreaks<br>Linebreaks<br>Linebreaks", "*x*<sup>2</sup> + 5*x* + *C*<sub>*i*</sub>", "Some <span style='color:blue'>blue text **in bold.**</span><br>And *italics text.*<br> And some <span style='font-size:18pt; color:black'>large</span> text." ) labels2 <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1" # "gC \n mm/d" ) df <- data.frame( x = c(.2, .1, .5, .9), y = c(.8, .4, .1, .5), hjust = c(0.5, 0, 0, 1), vjust = c(0.5, 1, 0, 0.5), angle = c(0, 0, 45, -45), color = c("black", "blue", "black", "red"), fill = c("cornsilk", "white", "lightblue1", "white") ) fun <- function(labels) { df$label = labels ggplot(df, aes(x, y, label = label, angle = angle, color = color, hjust = hjust, vjust = vjust)) + geom_richtext2( fill = NA, label.color = NA, # remove background and outline label.padding = grid::unit(rep(0, 4), "pt") # remove padding ) + geom_point(color = "black", size = 2) + scale_color_identity() + xlim(0, 1) + ylim(0, 1) } fun(labels1) fun(labels2) # labels without frame or background are also possible
geom_spike
geom_spike( mapping = NULL, data = NULL, stat = "spike", position = "identity", ..., halfwin = 3, sd.times = 3, trs = NA, verbose = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_spike( mapping = NULL, data = NULL, stat = "spike", position = "identity", ..., halfwin = 3, sd.times = 3, trs = NA, verbose = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
halfwin |
halfwin of movmean, |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(data.table) library(ggplot2) data("GPP_US_MMS") dat = melt(GPP_US_MMS[, .(date, SM, GPP)], "date") ggplot(dat, aes(date, value)) + geom_line() + geom_movmean(halfwin = 5, linewidth = 1, alpha = 0.7, color = "pink") + # geom_movmean(halfwin = 5, show.diff=TRUE, linewidth = 0.2, alpha = 0.7, color = "red") + geom_spike(halfwin = 2, sd.times = 6, color = "red", verbose = TRUE) + # geom_spike(halfwin = 5, trs = 3, color = "blue") + facet_wrap(~variable, scales = "free_y")library(data.table) library(ggplot2) data("GPP_US_MMS") dat = melt(GPP_US_MMS[, .(date, SM, GPP)], "date") ggplot(dat, aes(date, value)) + geom_line() + geom_movmean(halfwin = 5, linewidth = 1, alpha = 0.7, color = "pink") + # geom_movmean(halfwin = 5, show.diff=TRUE, linewidth = 0.2, alpha = 0.7, color = "red") + geom_spike(halfwin = 2, sd.times = 6, color = "red", verbose = TRUE) + # geom_spike(halfwin = 5, trs = 3, color = "blue") + facet_wrap(~variable, scales = "free_y")
geom_taylor
geom_taylor( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., obs.colour = "black", obs.size = 5, show.obs.label = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )geom_taylor( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., obs.colour = "black", obs.size = 5, show.obs.label = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
obs.colour |
color of observed point. |
obs.size |
size of observed point. |
show.obs.label |
logical, whether to show the label of observed point. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(ggplot2) library(dplyr) data = dummy_model %>% group_by(model, variable) %>% group_modify(~taylor_data(.$obs, .$mod)) #%>% as.data.table() print(data) mar = 0.01 p = ggplot(data) + geom_taylor(aes2(sd.obs, sd.mod, R, color = model), obs.colour = "black", obs.size = 5) + # geom_point(aes(color = model), size = 5) + facet_wrap(~variable) + labs(color = NULL) + theme_bw() + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = c(1, 1) - c(1, 1/3)*mar, legend.justification = c(1, 1) ) p # p = last_plot() # Ipaper::write_fig(p, "Rplot.pdf")library(ggplot2) library(dplyr) data = dummy_model %>% group_by(model, variable) %>% group_modify(~taylor_data(.$obs, .$mod)) #%>% as.data.table() print(data) mar = 0.01 p = ggplot(data) + geom_taylor(aes2(sd.obs, sd.mod, R, color = model), obs.colour = "black", obs.size = 5) + # geom_point(aes(color = model), size = 5) + facet_wrap(~variable) + labs(color = NULL) + theme_bw() + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = c(1, 1) - c(1, 1/3)*mar, legend.justification = c(1, 1) ) p # p = last_plot() # Ipaper::write_fig(p, "Rplot.pdf")
ggplot_legend
ggplot_legend(g)ggplot_legend(g)
g |
A ggplot object |
A grob object
ggplot_multiaxis
ggplot_multiaxis(..., linewidth = 1.4, tck = 0.2, x = -0.02) ggplot_multiAxis(..., linewidth = 1.4, tck = 0.2, x = -0.02)ggplot_multiaxis(..., linewidth = 1.4, tck = 0.2, x = -0.02) ggplot_multiAxis(..., linewidth = 1.4, tck = 0.2, x = -0.02)
... |
ggplot2 objects, which should have axis.tick.y.right and axis.title.y.left |
linewidth |
line width of right axis line |
tck |
tick length of right axis |
library(ggplot2) library(rlang) library(gg.layers) plot_1var <- function(d, var, color = "black", lwd = 0.4, alpha = 0.6) { p <- ggplot(d, aes(date, !!sym(var))) + geom_line(color = color, linewidth = lwd, alpha = alpha) + # facet_wrap(~site) + scale_x_date(date_breaks = "1 year", date_labels = "%Y") + theme( panel.background = element_rect(fill = "transparent", color = "black"), plot.margin = margin(r = 5, l = 5, t = 2, b = 2), axis.ticks.y.left = element_line(color = color), axis.text.y.left = element_text(color = color), axis.title.y.left = element_text(color = color), axis.ticks.y.right = element_line(color = color), axis.text.y.right = element_text(color = color), axis.title.y.right = element_text(color = color, margin = margin(l = 2, r = 5)), panel.grid.major = element_blank(), # get rid of major grid panel.grid.minor = element_blank() ) # get rid of minor grid p } # GPP_US_MMS = d[year(date) >= 2013] # usethis::use_data(GPP_US_MMS) p_gpp <- plot_1var(GPP_US_MMS, "GPP", color = "green") p_sm <- plot_1var(GPP_US_MMS, "SM", color = "red") p_prcp <- plot_1var(GPP_US_MMS, "prcp", color = "blue") p <- ggplot_multiaxis(p_gpp, p_sm, p_prcp, x = -0.02, linewidth = 1.2) plibrary(ggplot2) library(rlang) library(gg.layers) plot_1var <- function(d, var, color = "black", lwd = 0.4, alpha = 0.6) { p <- ggplot(d, aes(date, !!sym(var))) + geom_line(color = color, linewidth = lwd, alpha = alpha) + # facet_wrap(~site) + scale_x_date(date_breaks = "1 year", date_labels = "%Y") + theme( panel.background = element_rect(fill = "transparent", color = "black"), plot.margin = margin(r = 5, l = 5, t = 2, b = 2), axis.ticks.y.left = element_line(color = color), axis.text.y.left = element_text(color = color), axis.title.y.left = element_text(color = color), axis.ticks.y.right = element_line(color = color), axis.text.y.right = element_text(color = color), axis.title.y.right = element_text(color = color, margin = margin(l = 2, r = 5)), panel.grid.major = element_blank(), # get rid of major grid panel.grid.minor = element_blank() ) # get rid of minor grid p } # GPP_US_MMS = d[year(date) >= 2013] # usethis::use_data(GPP_US_MMS) p_gpp <- plot_1var(GPP_US_MMS, "GPP", color = "green") p_sm <- plot_1var(GPP_US_MMS, "SM", color = "red") p_prcp <- plot_1var(GPP_US_MMS, "prcp", color = "blue") p <- ggplot_multiaxis(p_gpp, p_sm, p_prcp, x = -0.02, linewidth = 1.2) p
Good of fitting
GOF(obs, sim, w, include.cv = FALSE, include.r = TRUE) KGE(obs, sim, w = c(1, 1, 1), ...) NSE(obs, sim, w, ...)GOF(obs, sim, w, include.cv = FALSE, include.r = TRUE) KGE(obs, sim, w = c(1, 1, 1), ...) NSE(obs, sim, w, ...)
obs |
Numeric vector, observations |
sim |
Numeric vector, corresponding simulated values |
w |
Numeric vector, weights of every points. If w included, when calculating mean, Bias, MAE, RMSE and NSE, w will be taken into considered. |
include.cv |
If true, cv will be included. |
include.r |
If true, r and R2 will be included. |
... |
ignored |
RMSE root mean square error
NSE NASH coefficient
MAE mean absolute error
AI Agreement index (only good points (w == 1)) participate to
calculate. See details in Zhang et al., (2015).
Bias bias
Bias_perc bias percentage
n_sim number of valid obs
cv Coefficient of variation
R2 correlation of determination
R pearson correlation
pvalue pvalue of R
https://en.wikipedia.org/wiki/Coefficient_of_determination
https://en.wikipedia.org/wiki/Explained_sum_of_squares
https://en.wikipedia.org/wiki/Nash%E2%80%93Sutcliffe_model_efficiency_coefficient
Zhang Xiaoyang (2015), http://dx.doi.org/10.1016/j.rse.2014.10.012
obs = rnorm(100) sim = obs + rnorm(100)/4 GOF(obs, sim)obs = rnorm(100) sim = obs + rnorm(100)/4 GOF(obs, sim)
guide_coloursteps2 #' @param title A title for the guide.
guide_coloursteps2( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c("colour", "color", "fill"), barheight = unit(0.9, "npc"), ... ) guide_colorsteps2( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c("colour", "color", "fill"), barheight = unit(0.9, "npc"), ... )guide_coloursteps2( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c("colour", "color", "fill"), barheight = unit(0.9, "npc"), ... ) guide_colorsteps2( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c("colour", "color", "fill"), barheight = unit(0.9, "npc"), ... )
theme |
A theme object for rendering the guide. |
alpha |
Alpha transparency level. |
even.steps |
Logical; should the steps be evenly spaced? |
show.limits |
Logical; should the limits be shown? |
direction |
Direction of the guide ("horizontal" or "vertical"). |
reverse |
Logical; should the guide be reversed? |
order |
Order of the guide. |
available_aes |
Available aesthetics for this guide. |
barheight |
Height of the color bar. Deprecated in ggplot2 3.5.0. |
... |
Additional arguments passed to the guide. #' @example R/examples/ex-stat_cut.R |
layer_barchart
layer_barchart( mapping = NULL, data = NULL, brks, cols, x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0), fontsize = 12, theme = NULL, ... ) geom_barchart( mapping = NULL, data = NULL, brks, cols, x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0), fontsize = 12, theme = NULL, ... )layer_barchart( mapping = NULL, data = NULL, brks, cols, x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0), fontsize = 12, theme = NULL, ... ) geom_barchart( mapping = NULL, data = NULL, brks, cols, x = 0, y = 0, width = unit(0.5, "npc"), height = unit(0.5, "npc"), just = c(0, 0), fontsize = 12, theme = NULL, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
x |
A numeric vector or unit object specifying x-location. |
y |
A numeric vector or unit object specifying y-location. |
width |
A numeric vector or unit object specifying width. |
height |
A numeric vector or unit object specifying height. |
just |
Adjustment for column placement. Set to |
... |
Other arguments passed on to
|
library(gg.layers) library(ggplot2) library(rcolors) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() brks = seq(0.9, 1, 0.025) nbrk = length(brks) - 1 cols <- get_color(rcolors$amwg256, nbrk) # the part of not significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + layer_barchart(aes(z = perc), width = unit(0.3, "npc"), height = unit(0.3, "npc"), brks = brks, cols = cols)library(gg.layers) library(ggplot2) library(rcolors) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() brks = seq(0.9, 1, 0.025) nbrk = length(brks) - 1 cols <- get_color(rcolors$amwg256, nbrk) # the part of not significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + layer_barchart(aes(z = perc), width = unit(0.3, "npc"), height = unit(0.3, "npc"), brks = brks, cols = cols)
layer_PosNeg
layer_PosNeg(mapping = NULL, data = NULL, x = 0, y = 0, size = 12, ...) add_PosNeg( z, x = 0.5, y = 0.5, height.factor = 1.2, cols = c("blue", "red"), alpha = 0.8, ... ) layer_PosNeg_sign( mapping = NULL, data = NULL, x = 0.5, y = 0.5, height.factor = 1.2, size = 12, ... ) add_PosNeg_sign( z, mask, x = 0.5, y = 0.5, height.factor = 1.2, cols = c("blue", "red"), alpha = 0.8, ... )layer_PosNeg(mapping = NULL, data = NULL, x = 0, y = 0, size = 12, ...) add_PosNeg( z, x = 0.5, y = 0.5, height.factor = 1.2, cols = c("blue", "red"), alpha = 0.8, ... ) layer_PosNeg_sign( mapping = NULL, data = NULL, x = 0.5, y = 0.5, height.factor = 1.2, size = 12, ... ) add_PosNeg_sign( z, mask, x = 0.5, y = 0.5, height.factor = 1.2, cols = c("blue", "red"), alpha = 0.8, ... )
... |
other parameters to |
make_colorbar
make_colorbar( at, labels = NULL, labeller = format, space = "right", width = 2, height = 1, col = NULL, alpha = 1, pretty = FALSE, equispaced = TRUE, tick.number = 7, tck = 0.3, tck.padding = 0, raster = FALSE, interpolate = FALSE, tri.upper = NA, tri.lower = NA, legend.line = element_line(linewidth = 0.8), legend.box = element_rect(linewidth = 0.5), hjust = 0.5, vjust = 0.5, size = 12, family = "Times", legend.text.location = c(0.5, 0.5), legend.margin = bb_margin(), title = NULL, legend.text = element_text(hjust = 0.5), legend.title = element_text(), fct.title.height = 1.8, padding.left = unit(2, "points"), padding.right = unit(2, "points"), ..., draw = FALSE, vp = NULL )make_colorbar( at, labels = NULL, labeller = format, space = "right", width = 2, height = 1, col = NULL, alpha = 1, pretty = FALSE, equispaced = TRUE, tick.number = 7, tck = 0.3, tck.padding = 0, raster = FALSE, interpolate = FALSE, tri.upper = NA, tri.lower = NA, legend.line = element_line(linewidth = 0.8), legend.box = element_rect(linewidth = 0.5), hjust = 0.5, vjust = 0.5, size = 12, family = "Times", legend.text.location = c(0.5, 0.5), legend.margin = bb_margin(), title = NULL, legend.text = element_text(hjust = 0.5), legend.title = element_text(), fct.title.height = 1.8, padding.left = unit(2, "points"), padding.right = unit(2, "points"), ..., draw = FALSE, vp = NULL )
legend.box |
arrangement of multiple legends ("horizontal" or "vertical") |
hjust, vjust
|
used in |
legend.margin |
the margin around each legend ( |
title |
all title elements: plot, axes, legends ( |
legend.text |
|
legend.title |
title of legend ( |
padding.left, padding.right
|
padding in the left and right of the legend |
... |
additional element specifications not part of base ggplot2. In general,
these should also be defined in the |
draw |
A logical value indicating whether graphics output should be produced. |
vp |
A Grid viewport object (or NULL). |
library(ggplot2) library(rcolors) library(magrittr) library(glue) ## example 01 spaces <- c("right", "left", "top", "bottom") # %>% set_names(., .) make_cbar <- function(brks, space, outfile = NULL) { # brks <- 1:5 nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) g <- make_colorbar( at = brks, col = cols, space = space, title = space ) if (!is.null(outfile)) { if (require(Ipaper)) Ipaper::write_fig(g, outfile, 10, 6) } g } brks = 1:5 %>% c(-Inf, ., Inf) spaces <- c("right", "left", "top", "bottom") ps = lapply(spaces, function(space) { fout = glue("cbar_{space}.pdf") fout = NULL make_cbar(brks, space, fout) }) g = cowplot::plot_grid(plotlist = ps) # g = patchwork::wrap_plots(ps) # grid.newpage(); grid.draw(g) # Ipaper::write_fig(g, "Rplot.pdf", 10, 6) # uncomment if want to show figure ## example 02 brks = c(-Inf, -1, 0, 1, 3, 6, 9, Inf) # brks = 1:10 nbrk = length(brks) - 1 cols = get_color(rcolors$amwg256, nbrk) spaces = c("right", "left", "top", "bottom") #%>% set_names(., .) params <- list( at = brks, col = cols, height = 1, tck = 0.4, # padding.left = unit(2, "points"), # padding.right = unit(2, "points"), space = spaces[1], # legend.line = element_line(size = 0.1, linetype = 1, color = "black"), # legend.text = element_text(hjust = 0.5), legend.text.location = c(0.2, 0.5), # legend.margin = bb_margin(t = 0.1), # legend.text.just = c(0.5, 0.5), # title = NULL, title = "d/decade", fct.title.height = 3, legend.title = element_text(size = 14) # legend.box = element_rect(size = 0.5), # legend.line = element_line(size = 1), # legend.text = list(fontfamily = "Times", cex = 1.1), # hjust = 0.5 ) cbar <- do.call(make_colorbar, params) # write_fig(cbar, "a.pdf", 0.9, 6) # cowplot::plot_grid(plotlist = lst) p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl) p + cbar p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl, nrow = 2) add_colorbar(p, cbar) ## Test the bottom params$space = "bottom" params$title = "" cbar2 <- do.call(make_colorbar, params) add_colorbar(p, cbar2, space = "bottom", title = "(mm/y)", legend.title = element_text(hjust = -5, vjust = -3, family = "Times")) # Another option title = element_grob_text(element_text(family = "Times", hjust = 1, vjust = 0, size = 12), label = "(mm/y)", x = 0.98, y = 0.09) add_colorbar(p, cbar2, space = "bottom") %>% add_grob(title)library(ggplot2) library(rcolors) library(magrittr) library(glue) ## example 01 spaces <- c("right", "left", "top", "bottom") # %>% set_names(., .) make_cbar <- function(brks, space, outfile = NULL) { # brks <- 1:5 nbrk <- length(brks) - 1 cols <- rcolors::get_color("amwg256", nbrk) g <- make_colorbar( at = brks, col = cols, space = space, title = space ) if (!is.null(outfile)) { if (require(Ipaper)) Ipaper::write_fig(g, outfile, 10, 6) } g } brks = 1:5 %>% c(-Inf, ., Inf) spaces <- c("right", "left", "top", "bottom") ps = lapply(spaces, function(space) { fout = glue("cbar_{space}.pdf") fout = NULL make_cbar(brks, space, fout) }) g = cowplot::plot_grid(plotlist = ps) # g = patchwork::wrap_plots(ps) # grid.newpage(); grid.draw(g) # Ipaper::write_fig(g, "Rplot.pdf", 10, 6) # uncomment if want to show figure ## example 02 brks = c(-Inf, -1, 0, 1, 3, 6, 9, Inf) # brks = 1:10 nbrk = length(brks) - 1 cols = get_color(rcolors$amwg256, nbrk) spaces = c("right", "left", "top", "bottom") #%>% set_names(., .) params <- list( at = brks, col = cols, height = 1, tck = 0.4, # padding.left = unit(2, "points"), # padding.right = unit(2, "points"), space = spaces[1], # legend.line = element_line(size = 0.1, linetype = 1, color = "black"), # legend.text = element_text(hjust = 0.5), legend.text.location = c(0.2, 0.5), # legend.margin = bb_margin(t = 0.1), # legend.text.just = c(0.5, 0.5), # title = NULL, title = "d/decade", fct.title.height = 3, legend.title = element_text(size = 14) # legend.box = element_rect(size = 0.5), # legend.line = element_line(size = 1), # legend.text = list(fontfamily = "Times", cex = 1.1), # hjust = 0.5 ) cbar <- do.call(make_colorbar, params) # write_fig(cbar, "a.pdf", 0.9, 6) # cowplot::plot_grid(plotlist = lst) p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl) p + cbar p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl, nrow = 2) add_colorbar(p, cbar) ## Test the bottom params$space = "bottom" params$title = "" cbar2 <- do.call(make_colorbar, params) add_colorbar(p, cbar2, space = "bottom", title = "(mm/y)", legend.title = element_text(hjust = -5, vjust = -3, family = "Times")) # Another option title = element_grob_text(element_text(family = "Times", hjust = 1, vjust = 0, size = 12), label = "(mm/y)", x = 0.98, y = 0.09) add_colorbar(p, cbar2, space = "bottom") %>% add_grob(title)
scale_fill_gradientn2
scale_fill_gradientn2( ..., colours, values = NULL, space = "Lab", na.value = "transparent", guide = colourbar_triangle(), oob = censor2, aesthetics = "colour", colors )scale_fill_gradientn2( ..., colours, values = NULL, space = "Lab", na.value = "transparent", guide = colourbar_triangle(), oob = censor2, aesthetics = "colour", colors )
... |
Arguments passed on to
|
colours, colors
|
Vector of colours to use for n-colour gradient. |
values |
if colours should not be evenly positioned along the gradient
this vector gives the position (between 0 and 1) for each colour in the
|
space |
colour space in which to calculate gradient. Must be "Lab" - other values are deprecated. |
na.value |
Colour to use for missing values |
guide |
Type of legend. Use |
oob |
function that handles limits outside of the scale limits |
aesthetics |
Character string or vector of character strings listing the
name(s) of the aesthetic(s) that this scale works with. This can be useful, for
example, to apply colour settings to the |
st_hatched_polygon
st_hatched_polygon(x, density = 2, angle = 45, fillOddEven = FALSE)st_hatched_polygon(x, density = 2, angle = 45, fillOddEven = FALSE)
x |
sf polygon object |
density |
the density of shading lines, in lines per inch. The default value of NULL means that no shading lines are drawn. A zero value of density means no shading nor filling whereas negative values and NA suppress shading (and so allow color filling). |
angle |
the slope of shading lines, given as an angle in degrees (counter-clockwise). |
fillOddEven |
logical controlling the polygon shading mode: see
below for details. Default |
An hatched area, sf lines
library(gg.layers) library(ggplot2) data("d_trendPerc") d = d_trendPerc %>% subset(perc >= 0.99) %>% .[, 1:2] poly = st_point2poly(d) hatches = st_hatched_polygon(poly) # ggplot(hatches) + geom_sf()library(gg.layers) library(ggplot2) data("d_trendPerc") d = d_trendPerc %>% subset(perc >= 0.99) %>% .[, 1:2] poly = st_point2poly(d) hatches = st_hatched_polygon(poly) # ggplot(hatches) + geom_sf()
st_point2poly
st_point2poly(xyz, crs = 4326) df2rast(xyz) rast2poly(r, crs = 4326) st_dissolve(x, by = NULL, ...)st_point2poly(xyz, crs = 4326) df2rast(xyz) rast2poly(r, crs = 4326) st_dissolve(x, by = NULL, ...)
xyz |
matrix or data.frame with at least three columns: x and y coordinates, and values (z). There may be several 'z' variables (columns) |
crs |
one of (i) character: a string accepted by GDAL, (ii) integer, a valid EPSG value (numeric), or (iii) an object of class crs. |
https://gis.stackexchange.com/questions/192771/how-to-speed-up-raster-to-polygon-conversion-in-r
stat_cut
stat_cut( mapping = NULL, data = NULL, geom = "point", position = "identity", ..., breaks = NULL, include.lowest = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) StatCutstat_cut( mapping = NULL, data = NULL, geom = "point", position = "identity", ..., breaks = NULL, include.lowest = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) StatCut
An object of class StatCut (inherits from StatIdentity, Stat, ggproto, gg) of length 6.
library(rcolors) library(ggplot2) library(magrittr) df = data.frame(x = 1:10, y = 1:10, z = 1:10) brks <- c(2, 4, 6, 8) %>% c(-Inf, ., Inf) # 这里要包含 nbrk <- length(brks) - 1 cols = get_color(rcolors$amwg256, nbrk) ggplot(df, aes(x, y, z = x)) + stat_cut(aes(color = after_stat(level)), breaks = brks, geom = "point") + scale_color_manual( values = cols, guide = guide_coloursteps2(title = "lgd", barheight = unit(0.8, "npc")) ) ## another option: use `scale_color_stepsn` # example 2 # ! unable to accurately control the used colors ggplot(df, aes(x, y, color = x)) + geom_point() + scale_color_stepsn( colors = cols, breaks = brks, guide = guide_coloursteps2(title = "lgd") ) + theme( legend.title = element_blank(), legend.margin = margin(l = -2) ) # example 3 df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 brks = c(10, 15, 25, 50) nbrk <- length(brks) + 1 cols = get_color(rcolors$amwg256, nbrk) # This can be changed with the `even.steps` argument ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) + scale_fill_stepsn( colors = cols, breaks = brks, guide = guide_colorsteps2() ) + theme( legend.title = element_blank(), legend.margin = margin(l = -2) )library(rcolors) library(ggplot2) library(magrittr) df = data.frame(x = 1:10, y = 1:10, z = 1:10) brks <- c(2, 4, 6, 8) %>% c(-Inf, ., Inf) # 这里要包含 nbrk <- length(brks) - 1 cols = get_color(rcolors$amwg256, nbrk) ggplot(df, aes(x, y, z = x)) + stat_cut(aes(color = after_stat(level)), breaks = brks, geom = "point") + scale_color_manual( values = cols, guide = guide_coloursteps2(title = "lgd", barheight = unit(0.8, "npc")) ) ## another option: use `scale_color_stepsn` # example 2 # ! unable to accurately control the used colors ggplot(df, aes(x, y, color = x)) + geom_point() + scale_color_stepsn( colors = cols, breaks = brks, guide = guide_coloursteps2(title = "lgd") ) + theme( legend.title = element_blank(), legend.margin = margin(l = -2) ) # example 3 df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 brks = c(10, 15, 25, 50) nbrk <- length(brks) + 1 cols = get_color(rcolors$amwg256, nbrk) # This can be changed with the `even.steps` argument ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) + scale_fill_stepsn( colors = cols, breaks = brks, guide = guide_colorsteps2() ) + theme( legend.title = element_blank(), legend.margin = margin(l = -2) )
stat_gof
stat_gof( mapping = NULL, data = NULL, geom = GeomRichTextNpc, position = "identity", na.rm = FALSE, show.legend = NA, show.bias = TRUE, label.format = fmt_gof, x = 0.05, y = 0.95, inherit.aes = TRUE, ... ) geom_gof( mapping = NULL, data = NULL, stat = StatGOF, position = "identity", ..., show.bias = TRUE, label.format = fmt_gof, x = 0, y = 1, hjust = 0, vjust = 1, size = 5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_reg( mapping = NULL, data = NULL, formula = y ~ x, digits = 2, units = "", format = paste0("Slope = {str_num(slope, digits)}{unit}", ", p-value = {str_num(pvalue, digits)}"), fun_slope = NULL, x = 0, y = 1, hjust = 0, vjust = 1, mar = 0.03, height.factor = 1.2, family = "Times", color = NULL, position = "dodge", ... )stat_gof( mapping = NULL, data = NULL, geom = GeomRichTextNpc, position = "identity", na.rm = FALSE, show.legend = NA, show.bias = TRUE, label.format = fmt_gof, x = 0.05, y = 0.95, inherit.aes = TRUE, ... ) geom_gof( mapping = NULL, data = NULL, stat = StatGOF, position = "identity", ..., show.bias = TRUE, label.format = fmt_gof, x = 0, y = 1, hjust = 0, vjust = 1, size = 5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_reg( mapping = NULL, data = NULL, formula = y ~ x, digits = 2, units = "", format = paste0("Slope = {str_num(slope, digits)}{unit}", ", p-value = {str_num(pvalue, digits)}"), fun_slope = NULL, x = 0, y = 1, hjust = 0, vjust = 1, mar = 0.03, height.factor = 1.2, family = "Times", color = NULL, position = "dodge", ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
position |
"dodge" or "identity" |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
show.bias |
whether to show bias |
label.format |
format string for label, default |
x |
A numeric vector or unit object specifying x-values. |
y |
A numeric vector or unit object specifying y-values. |
inherit.aes |
If |
... |
Other arguments passed on to |
stat |
The statistical transformation to use on the data for this layer, as a string. |
hjust |
Horizontal justification (in |
vjust |
Vertical justification (in |
formula |
an object of class |
digits |
the number of significant digits to be
passed to |
units |
A Vector with the length of subplots |
family |
The typeface to use. The validity of this value will depend on
the graphics device being used for rendering the plot. See
the systemfonts vignette
for guidance on the best way to access fonts installed on your computer.
The values |
b: the object returned by broom::tidy()
s: the object returned by broom::glance()
*R*^2 = {str_num(s$r.squared, digits)}
slope:
pvalue:
pcode: significant code, e.g., **, *, -
No return. This function is used to calculate data for gglot2 geom_*,
just like ggplot2::stat_smooth().
library(ggplot2) library(data.table) dat <- data.table(mtcars) dat$cyl <- as.factor(dat$cyl) table(dat$cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, mar = 0, position = "none") + facet_wrap(~cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, position = "dodge", height.factor = 1.2, unit = "gC m^-2 d^-1") ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, position = "none", height.factor = 1.2, unit = "gC m^-2 d^-1") + facet_wrap(~cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_gof(x = 0, y = 1) + # stat_reg(data = subset(dat, cyl == 4), y = 1, color = "red") + # stat_reg(data = subset(dat, cyl == 6), y = 0.8) + facet_wrap(~cyl)library(ggplot2) library(data.table) dat <- data.table(mtcars) dat$cyl <- as.factor(dat$cyl) table(dat$cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, mar = 0, position = "none") + facet_wrap(~cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, position = "dodge", height.factor = 1.2, unit = "gC m^-2 d^-1") ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_reg(data = dat[cyl != 4], y = 1, position = "none", height.factor = 1.2, unit = "gC m^-2 d^-1") + facet_wrap(~cyl) ggplot(dat, aes(wt, mpg, color = cyl)) + geom_point() + stat_gof(x = 0, y = 1) + # stat_reg(data = subset(dat, cyl == 4), y = 1, color = "red") + # stat_reg(data = subset(dat, cyl == 6), y = 0.8) + facet_wrap(~cyl)
stat_gof2
stat_gof2( mapping = NULL, data = NULL, geom = GeomRichTextNpc, position = "identity", na.rm = FALSE, show.legend = NA, show.bias = TRUE, label.format = fmt_gof, x = 0.05, y = 0.95, inherit.aes = TRUE, ... ) geom_gof2( mapping = NULL, data = NULL, stat = StatGOF2, position = "identity", ..., show.bias = TRUE, label.format = fmt_gof, eval.flood = FALSE, x = 0, y = 1, hjust = 0, vjust = 1, size = 5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )stat_gof2( mapping = NULL, data = NULL, geom = GeomRichTextNpc, position = "identity", na.rm = FALSE, show.legend = NA, show.bias = TRUE, label.format = fmt_gof, x = 0.05, y = 0.95, inherit.aes = TRUE, ... ) geom_gof2( mapping = NULL, data = NULL, stat = StatGOF2, position = "identity", ..., show.bias = TRUE, label.format = fmt_gof, eval.flood = FALSE, x = 0, y = 1, hjust = 0, vjust = 1, size = 5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
position |
Position adjustment, either as a string, or the result of
a call to a position adjustment function. Cannot be jointy specified with
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
label.format |
default value:
|
x |
A numeric vector or unit object specifying x-values. |
y |
A numeric vector or unit object specifying y-values. |
inherit.aes |
If |
... |
Other arguments passed on to |
stat |
The statistical transformation to use on the data for this layer, as a string. |
No return. This function is used to calculate data for gglot2
geom_*, just like ggplot2::stat_smooth().
obs: observed
sim: simulated
library(ggplot2) library(data.table) dates <- seq(as.Date("2010-01-01"), length.out = 32, by = "day") dat <- data.table(mtcars) %>% cbind(date = dates, .) dat$cyl <- as.factor(dat$cyl) # table(dat$cyl) ggplot(dat, aes(date, mpg, color = cyl)) + stat_gof2(aes(obs = mpg, sim = wt), x = 0, y = 1) + geom_point() + facet_wrap(~cyl) ## Example 2 dat = GPP_US_MMS ggplot(dat, aes(date, GPP)) + geom_line() + stat_gof2(aes(obs=GPP, sim=SM), x = 0, y = 1) ## dat = data.table( obs = c(10, 12, 15, 14, 13, 16, 18, 20, 19, 22), sim = c(11, 13, 14, 15, 12, 17, 17, 21, 20, 20), sim2 = c(11, 13, 14, 15, 12, 17, 17, 21, 20, 25), group = rep(c("A", "B"), each = 5) ) showtext::showtext_auto() fmt_gof <- "*NSE* = {str_num(NSE,2)}, *R^2* = {str_num(R2, 2)}" p = ggplot(dat, aes(obs, sim)) + geom_point() + stat_gof2(aes(obs = obs, sim = sim), x = 0, y = 1, eval.flood = TRUE, show.bias = FALSE, label.format = fmt_gof, size = 6) + stat_gof2(aes(obs = obs, sim = sim2), x = 0, y = 0.9, eval.flood = TRUE, show.bias = FALSE, label.format = fmt_gof, size = 6) # write_fig(p, "d:/Rplot.pdf", 10, 5)library(ggplot2) library(data.table) dates <- seq(as.Date("2010-01-01"), length.out = 32, by = "day") dat <- data.table(mtcars) %>% cbind(date = dates, .) dat$cyl <- as.factor(dat$cyl) # table(dat$cyl) ggplot(dat, aes(date, mpg, color = cyl)) + stat_gof2(aes(obs = mpg, sim = wt), x = 0, y = 1) + geom_point() + facet_wrap(~cyl) ## Example 2 dat = GPP_US_MMS ggplot(dat, aes(date, GPP)) + geom_line() + stat_gof2(aes(obs=GPP, sim=SM), x = 0, y = 1) ## dat = data.table( obs = c(10, 12, 15, 14, 13, 16, 18, 20, 19, 22), sim = c(11, 13, 14, 15, 12, 17, 17, 21, 20, 20), sim2 = c(11, 13, 14, 15, 12, 17, 17, 21, 20, 25), group = rep(c("A", "B"), each = 5) ) showtext::showtext_auto() fmt_gof <- "*NSE* = {str_num(NSE,2)}, *R^2* = {str_num(R2, 2)}" p = ggplot(dat, aes(obs, sim)) + geom_point() + stat_gof2(aes(obs = obs, sim = sim), x = 0, y = 1, eval.flood = TRUE, show.bias = FALSE, label.format = fmt_gof, size = 6) + stat_gof2(aes(obs = obs, sim = sim2), x = 0, y = 0.9, eval.flood = TRUE, show.bias = FALSE, label.format = fmt_gof, size = 6) # write_fig(p, "d:/Rplot.pdf", 10, 5)
geom_interval
stat_interval( mapping = NULL, data = NULL, geom = GeomInterval, position = "identity", interval = 0.8, fun_middle = "median", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) geom_interval( mapping = NULL, data = NULL, stat = "interval", position = "identity", ..., fun_middle = "median", interval = 0.8, alpha.line = 0.7, param_ensemble = list(), param_slope = list(alpha = 1, linewidth = 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )stat_interval( mapping = NULL, data = NULL, geom = GeomInterval, position = "identity", interval = 0.8, fun_middle = "median", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) geom_interval( mapping = NULL, data = NULL, stat = "interval", position = "identity", ..., fun_middle = "median", interval = 0.8, alpha.line = 0.7, param_ensemble = list(), param_slope = list(alpha = 1, linewidth = 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
interval |
interval of confidence interval, default is 0.8 |
fun_middle |
function to calculate middle value, default is median |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
Other arguments passed on to
|
stat |
The statistical transformation to use on the data for this layer.
When using a
|
alpha.line |
alpha of ensemble line |
param_ensemble |
list of parameters for ensemble line |
param_slope |
list of parameters for slope line |
library(ggplot2) df <- CMIP6_HWD p <- ggplot(df, aes(year, value, color = prob, fill = prob)) # both line and fill p + geom_interval(alpha = 0.2, alpha.line = 1, linewidth = 0.7, linetype = 2, # for ensemble line param_slope = list(linewidth = 1, alpha = 1, linetype = 1), # slope line interval = 0.8, fun_middle = "mean") # only line p + geom_interval( fill = "NA", alpha = 0.4, interval = 0.8, fun_middle = "mean", linewidth = 0.4 ) + theme(legend.key = element_rect(fill = "NA")) # only fill p + geom_interval( color = "NA", key_glyph = "polygon2", alpha = 0.4, interval = 0.8, fun_middle = "mean", linewidth = 0.4 ) + theme(legend.key = element_rect(fill = "NA"))library(ggplot2) df <- CMIP6_HWD p <- ggplot(df, aes(year, value, color = prob, fill = prob)) # both line and fill p + geom_interval(alpha = 0.2, alpha.line = 1, linewidth = 0.7, linetype = 2, # for ensemble line param_slope = list(linewidth = 1, alpha = 1, linetype = 1), # slope line interval = 0.8, fun_middle = "mean") # only line p + geom_interval( fill = "NA", alpha = 0.4, interval = 0.8, fun_middle = "mean", linewidth = 0.4 ) + theme(legend.key = element_rect(fill = "NA")) # only fill p + geom_interval( color = "NA", key_glyph = "polygon2", alpha = 0.4, interval = 0.8, fun_middle = "mean", linewidth = 0.4 ) + theme(legend.key = element_rect(fill = "NA"))
prob density
stat_prob_2d( mapping = NULL, data = NULL, geom = "density_2d", position = "identity", ..., contour = TRUE, contour_var = "density", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )stat_prob_2d( mapping = NULL, data = NULL, geom = "density_2d", position = "identity", ..., contour = TRUE, contour_var = "density", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Use to override the default connection between stat_prob_2d. |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Arguments passed on to
|
contour |
If |
contour_var |
Character string identifying the variable to contour
by. Can be one of |
n |
Number of grid points in each direction. |
h |
Bandwidth (vector of length two). If |
adjust |
A multiplicative bandwidth adjustment to be used if 'h' is
'NULL'. This makes it possible to adjust the bandwidth while still
using the a bandwidth estimator. For example, |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
library(ggplot2) # Data n = 200 set.seed(1) a <- data.frame( x=rnorm(n, 10, 1.9), y=rnorm(n, 10, 1.2) ) b <- data.frame( x=rnorm(n, 14.5, 1.9), y=rnorm(n, 14.5, 1.9) ) c <- data.frame( x=rnorm(n, 9.5, 1.9), y=rnorm(n, 15.5, 1.9) ) data <- rbind(a,b,c) # Show the area only ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(fill = ..level.., color =..level.. ), geom = "polygon") ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(fill = ..level..), geom = "polygon", color = "white") ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(color =..level.. ), geom = "path")library(ggplot2) # Data n = 200 set.seed(1) a <- data.frame( x=rnorm(n, 10, 1.9), y=rnorm(n, 10, 1.2) ) b <- data.frame( x=rnorm(n, 14.5, 1.9), y=rnorm(n, 14.5, 1.9) ) c <- data.frame( x=rnorm(n, 9.5, 1.9), y=rnorm(n, 15.5, 1.9) ) data <- rbind(a,b,c) # Show the area only ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(fill = ..level.., color =..level.. ), geom = "polygon") ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(fill = ..level..), geom = "polygon", color = "white") ggplot(data, aes(x=x, y=y) ) + stat_prob_2d(aes(color =..level.. ), geom = "path")
geom_signHatch
stat_signHatch( mapping = NULL, data = NULL, geom = "sf", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., density = 1, angle = 45 ) geom_signHatch( mapping = aes(), data = NULL, stat = "signHatch", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., density = 1, angle = 45 )stat_signHatch( mapping = NULL, data = NULL, geom = "sf", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., density = 1, angle = 45 ) geom_signHatch( mapping = aes(), data = NULL, stat = "signHatch", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., density = 1, angle = 45 )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
show.legend |
logical. Should this layer be included in the legends?
You can also set this to one of "polygon", "line", and "point" to override the default legend. |
inherit.aes |
If |
... |
Other arguments passed on to
|
density |
the density of shading lines, in lines per inch. The default value of NULL means that no shading lines are drawn. A zero value of density means no shading nor filling whereas negative values and NA suppress shading (and so allow color filling). |
angle |
the slope of shading lines, given as an angle in degrees (counter-clockwise). |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
geom_signHatch() requires the following aesthetics:
x:
y:
mask:
library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) #%>% as.data.frame() ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + # geom_sf(data = shp) + geom_signHatch(data = d_mask, aes(x, y, mask = mask), color = "red")library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) #%>% as.data.frame() ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + # geom_sf(data = shp) + geom_signHatch(data = d_mask, aes(x, y, mask = mask), color = "red")
stat_signPattern
stat_signPattern( mapping = NULL, data = NULL, geom = "sf_pattern", position = "identity", show.legend = NA, inherit.aes = TRUE, ... )stat_signPattern( mapping = NULL, data = NULL, geom = "sf_pattern", position = "identity", show.legend = NA, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
other parameters to |
library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() # significant part; geom_sf_pattern still has bug unsolved. ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + stat_signPattern(data = d_mask, aes(x, y, mask = mask), fill = "transparent", color = "red", pattern_density = 0.02) # insignificant ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + stat_signPattern(data = d_mask, aes(x, y, mask = !mask), fill = "transparent", color = "red", pattern_density = 0.02) #-> p # Ipaper::write_fig(p, "temp.pdf")library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() # significant part; geom_sf_pattern still has bug unsolved. ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + stat_signPattern(data = d_mask, aes(x, y, mask = mask), fill = "transparent", color = "red", pattern_density = 0.02) # insignificant ggplot() + geom_raster(data = d_trendPerc, aes(x, y, fill = perc)) + stat_signPattern(data = d_mask, aes(x, y, mask = !mask), fill = "transparent", color = "red", pattern_density = 0.02) #-> p # Ipaper::write_fig(p, "temp.pdf")
stat_signPoint
stat_signPoint( mapping = NULL, data = NULL, geom = "point", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., fact = 1 ) geom_signPoint( mapping = aes(), data = NULL, stat = "signPoint", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., fact = 1 )stat_signPoint( mapping = NULL, data = NULL, geom = "point", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., fact = 1 ) geom_signPoint( mapping = aes(), data = NULL, stat = "signPoint", position = "identity", show.legend = NA, inherit.aes = TRUE, ..., fact = 1 )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
show.legend |
logical. Should this layer be included in the legends?
You can also set this to one of "polygon", "line", and "point" to override the default legend. |
inherit.aes |
If |
... |
Other arguments passed on to
|
fact |
postive integer. Plot one point in |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
geom_signPoint() requires the following aesthetics:
x:
y:
mask (optional): Boolean, mask=TRUE is regarded as significant.
Only plot regions with mask = TRUE.
library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() # the part of not significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_signPoint(aes(mask = !mask), fact = 2, shape = 4) # significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_signPoint(aes(mask = mask), fact = 2) ## Another option fact = 2 ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_point(data = ~ resample_points(.x, fact))library(gg.layers) library(ggplot2) data("d_trendPerc") d_mask <- mutate(d_trendPerc, mask = perc <= 0.99) # %>% as.data.frame() # the part of not significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_signPoint(aes(mask = !mask), fact = 2, shape = 4) # significant ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_signPoint(aes(mask = mask), fact = 2) ## Another option fact = 2 ggplot(data = d_mask, aes(x, y)) + geom_raster(aes(fill = perc)) + geom_point(data = ~ resample_points(.x, fact))
markdown superscript and subscript
str_mk(x) label_mk(labels, ...)str_mk(x) label_mk(labels, ...)
x |
character vector |
labels |
character vector |
... |
ignored |
Dongdong Kong
x <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1", "gC \n mm/d" ) str_mk(x) ## use str_mk in ggplot library(ggplot2) d <- data.frame( x = 1:3, y = 1:3, varname = c("T_min", "T_max", "T_avg") ) ggplot(d, aes(x, y)) + geom_point() + geom_richtext(aes(label = varname), x = 2, y = 2) + facet_wrap(~varname, labeller = label_mk) + theme( strip.text = element_markdown(face = "bold") )x <- c( "gC m^{-2} d^{-1}", "gC m^-2 d^-1", "gC m_{-2} d_{-1}", "gC m_-2 d_-1", "gC \n mm/d" ) str_mk(x) ## use str_mk in ggplot library(ggplot2) d <- data.frame( x = 1:3, y = 1:3, varname = c("T_min", "T_max", "T_avg") ) ggplot(d, aes(x, y)) + geom_point() + geom_richtext(aes(label = varname), x = 2, y = 2) + facet_wrap(~varname, labeller = label_mk) + theme( strip.text = element_markdown(face = "bold") )
Rounding of Numbers, and convert to string
str_num(x, digits = 2)str_num(x, digits = 2)
x |
a numeric vector. Or, for |
digits |
integer indicating the number of decimal places
( |
format(round(2, 2)) # 2 str_num(2, 2) # 2.00format(round(2, 2)) # 2 str_num(2, 2) # 2.00