ggplot2 and a Stacked Bar Chart with Negative Values

Update: As of ggplot2 2.2.0, stacking for negative values is handled automatically, without having to create separate layers for the positive and negative values. If I understand what you’re looking for, the trick is to put the two positive and negative data in separate layers, and also to use stat = “identity”: dat <- read.table(text … Read more

How to extract the first n rows per group?

yep, just use .SD and index it as needed. DT[, .SD[1:2], by=date] date age name 1: 2000-01-01 3 Andrew 2: 2000-01-01 4 Ben 3: 2000-01-02 6 Adam 4: 2000-01-02 7 Bob Edited as per @eddi’s suggestion. @eddi’s suggestion is spot on: Use this instead, for speed: DT[DT[, .I[1:2], by = date]$V1] # using a slightly … Read more

dplyr filter with condition on multiple columns

A possible dplyr(0.5.0.9004 <= version < 1.0) solution is: # > packageVersion(‘dplyr’) # [1] ‘0.5.0.9004’ dataset %>% filter(!is.na(father), !is.na(mother)) %>% filter_at(vars(-father, -mother), all_vars(is.na(.))) Explanation: vars(-father, -mother): select all columns except father and mother. all_vars(is.na(.)): keep rows where is.na is TRUE for all the selected columns. note: any_vars should be used instead of all_vars if rows … Read more

Plotting bar charts on map using ggplot2?

Update 2016-12-23: The ggsubplot-package is no longer actively maintained and is archived on CRAN: Package ‘ggsubplot’ was removed from the CRAN repository.> Formerly available versions can be obtained from the archive.> Archived on 2016-01-11 as requested by the maintainer [email protected]. ggsubplot will not work with R versions >= 3.1.0. Install R 3.0.3 to run the … Read more

How to Reverse a string in R

From ?strsplit, a function that’ll reverse every string in a vector of strings: ## a useful function: rev() for strings strReverse <- function(x) sapply(lapply(strsplit(x, NULL), rev), paste, collapse=””) strReverse(c(“abc”, “Statistics”)) # [1] “cba” “scitsitatS”

How to plot just the legends in ggplot2?

Here are 2 approaches: Set Up Plot library(ggplot2) library(grid) library(gridExtra) my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() Cowplot approach # Using the cowplot package legend <- cowplot::get_legend(my_hist) grid.newpage() grid.draw(legend) Home grown approach Shamelessly stolen from: Inserting a table under the legend in a ggplot2 histogram ## Function to extract legend g_legend <- function(a.gplot){ … Read more