library(ggplot2)
Twisted polygon
The function below is based on a random process, and thus, results in a different output each time.
R
Library:
Function:
<- function(n_edges = 4, n_polygons = 10, range_values = c(-10,10),
random_polygons colors = c('#FA2FBD', RColorBrewer::brewer.pal(5, name = 'Pastel1'), '#235347'),
coord_polar = TRUE){
# Generates random polygons
# inspired by @venpopov from twitter
#
# Args:
# n_edges: number of edges of polygons
# n_polygons: number of random generated polygons
# range_values: range of values for color coding the polygons
# colors: color palette based on ggplot2 color brewer colors, e.g. 'Pastel1'
# coord_polar: polar coordinates TRUE/FALSE
#
# Returns:
# Plot of random polygons with emtpy background theme
#
# v1.0 SG, 31.12.2019
<- as.numeric(n_edges)
n_edges <- as.numeric(n_polygons)
n_polygons <- rep(1:n_polygons, each = n_edges)
ids <- rep(runif(n_polygons, -10, 10), each = n_edges)
values <- runif(n_edges*n_polygons, 1, 10)
x_coord <- runif(n_edges*n_polygons, 1, 10)
y_coord <- data.frame(id = ids,
df_polygons value = values,
x = x_coord,
y = y_coord)
<- ggplot2::ggplot(df_polygons, aes(x = x, y = y)) +
img geom_polygon(aes(fill = value, group = id)) +
scale_fill_gradientn(colors = colors) + # different color palettes: see ?scale_fill_distiller
theme_void() + # no background/grid/axes
theme(legend.position = "none",
panel.background = element_rect(fill = "#f8f8f6", color = NA),
plot.background = element_rect(fill = "#f8f8f6", color = NA),
#panel.grid = element_blank(), # Remove grid lines, which can look like a frame
panel.border = element_blank()
)
if (coord_polar == TRUE){
# structure + match.call to save call of the function
structure(img + coord_polar(), CALL = match.call() )
else {
} structure(img, CALL = match.call() )
} }
Apply function:
<- c('#FA2FBD', RColorBrewer::brewer.pal(5, name = 'Pastel1'), '#235347')
custom_colors
random_polygons(n_edges = 5,
n_polygons = 8,
coord_polar = TRUE,
colors = custom_colors)