Order Stacked Bar Graph by sum / total of all subgroups

The general (non ggplot-specific) answer is to use reorder() to reset the factor levels in a categorical column, based on some function of the other columns. ## Examine the default factor order levels(samp.data$fullname) ## Reorder fullname based on the the sum of the other columns samp.data$fullname <- reorder(samp.data$fullname, rowSums(samp.data[-1])) ## Examine the new factor order … Read more

How to add a number of observations per group and use group mean in ggplot2 boxplot?

Is this anything like what you’re after? With stat_summary, as requested: # function for number of observations give.n <- function(x){ return(c(y = median(x)*1.05, label = length(x))) # experiment with the multiplier to find the perfect position } # function for mean labels mean.n <- function(x){ return(c(y = median(x)*0.97, label = round(mean(x),2))) # experiment with the … Read more

How do I change the color value of just one value in ggplot2’s scale_fill_brewer?

The package RColorBrewer contains the palettes and you can use the function brewer.pal to return a colour palette of your choice. For example, a sequential blue palette of 5 colours: library(RColorBrewer) my.cols <- brewer.pal(5, “Blues”) my.cols [1] “#EFF3FF” “#BDD7E7” “#6BAED6” “#3182BD” “#08519C” You can get a list of valid palette names in the ?brewer.pal help … Read more

double dots in a ggplot

Unlike many other languages, in R, the dot is perfectly valid in identifiers. In this case, ..count.. is an identifier. However, there is special code in ggplot2 to detect this pattern, and to strip the dots. It feels unlikely that real code would use identifiers formatted like that, and so this is a neat way … Read more

Connecting across missing values with geom_line

Richie’s answer is very thorough, but I wanted to show something simpler. Since lines are not drawn to NA points, another approach is drop these points when drawing lines. This implicitly makes a linear interpolation between points (as straight lines do). Using dfr from Richie’s answer, without needing the calculation of z step: ggplot(dfr, aes(x,y)) … Read more