Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- my_special_fancy_legend = function(
- values, palette,
- direction = 1,
- borders = NA,
- legend_title = NULL,
- font_size = 11,
- expand_size = 1,
- width = 0.1,
- spacing = "natural"
- ) {
- require(ggplot2)
- require(RColorBrewer)
- if (!(spacing %in% c("natural", "constant"))) stop("spacing must be either 'natural' or 'constant'")
- values = as.numeric(values)
- colors = brewer.pal(length(values) - 1, palette)
- if (direction == -1) colors = rev(colors)
- values = sort(unique(values))
- inf_values = which(is.infinite(values))
- if (length(inf_values) != 0) values = values[-inf_values]
- plotcolors = colors
- labels = values
- if (spacing == "constant") {
- values = 1:length(values)
- }
- cbar_df = data.frame(stringsAsFactors = FALSE,
- y = values,
- yend = c(values[-1], NA),
- color = as.character(1:length(values))
- )[-length(values),]
- xmin = 1 - width/2
- xmax = 1 + width/2
- cbar_plot = ggplot(cbar_df, aes(xmin=xmin, xmax = xmax, ymin = y, ymax = yend, fill = color)) +
- geom_rect(show.legend = FALSE,
- color=borders)
- if (any(inf_values == 1)) { # < arrow
- firstv = values[1]
- polystart = data.frame(
- x = c(xmin, xmax, 1),
- y = c(rep(firstv, 2), firstv - diff(range(values)) / 10)
- )
- plotcolors = plotcolors[-1]
- cbar_plot = cbar_plot +
- geom_polygon(data=polystart, aes(x=x, y=y),
- show.legend = FALSE,
- inherit.aes = FALSE,
- fill = colors[1],
- color=borders)
- }
- if (any(inf_values > 1)) { # > arrow
- lastv = values[length(values)]
- polyend = data.frame(
- x = c(xmin, xmax, 1),
- y = c(rep(lastv, 2), lastv + diff(range(values)) / 10)
- )
- plotcolors = plotcolors[-length(plotcolors)]
- cbar_plot = cbar_plot +
- geom_polygon(data=polyend, aes(x=x, y=y),
- show.legend = FALSE,
- inherit.aes = FALSE,
- fill = colors[length(colors)],
- color=borders)
- }
- cbar_plot = cbar_plot +
- geom_segment(data=data.frame(y = values, yend = values), aes(y=y, yend=yend), x = xmin - 0.05, xend = xmax, inherit.aes = FALSE) +
- annotate(geom = 'text', x = xmin - 0.1, y = values, label = labels) +
- scale_x_continuous(expand = c(expand_size,expand_size)) +
- scale_fill_manual(values=plotcolors) +
- coord_flip() +
- theme_void(base_size = font_size)
- if (!is.null(legend_title)) {
- cbar_plot = cbar_plot +
- annotate(geom = 'text', x = xmax + 0.05, y = mean(range(values)), label = legend_title)
- }
- cbar_plot
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement