Left align two graph edges (ggplot)

Try this, gA <- ggplotGrob(A) gB <- ggplotGrob(B) maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5]) gA$widths[2:5] <- as.list(maxWidth) gB$widths[2:5] <- as.list(maxWidth) grid.arrange(gA, gB, ncol=1) Edit Here’s a more general solution (works with any number of plots) using a modified version of rbind.gtable included in gridExtra gA <- ggplotGrob(A) gB <- ggplotGrob(B) grid::grid.newpage() grid::grid.draw(rbind(gA, gB))

Side-by-side plots with ggplot2

Any ggplots side-by-side (or n plots on a grid) The function grid.arrange() in the gridExtra package will combine multiple plots; this is how you put two side by side. require(gridExtra) plot1 <- qplot(1) plot2 <- qplot(1) grid.arrange(plot1, plot2, ncol=2) This is useful when the two plots are not based on the same data, for example … Read more

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text. ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) + geom_bar(stat = “identity”) + geom_text(size = 3, position = position_stack(vjust = 0.5)) Also note that “position_stack() and position_fill() now stack values in the reverse … Read more

Issue when passing variable with dollar sign notation ($) to aes() in combination with facet_grid() or facet_wrap()

tl;dr Never use [ or $ inside aes(). Consider this illustrative example where the facetting variable f is purposely in a non-obvious order with respect to x d <- data.frame(x=1:10, f=rev(letters[gl(2,5)])) Now contrast what happens with these two plots, p1 <- ggplot(d) + facet_grid(.~f, labeller = label_both) + geom_text(aes(x, y=0, label=x, colour=f)) + ggtitle(“good mapping”) … Read more

Add regression line equation and R^2 on graph

Here is one solution # GET EQUATION AND R-SQUARED AS STRING # SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA lm_eqn <- function(df){ m <- lm(y ~ x, df); eq <- substitute(italic(y) == a + b %.% italic(x)*”,”~~italic(r)^2~”=”~r2, list(a = format(unname(coef(m)[1]), digits = 2), b = format(unname(coef(m)[2]), digits = 2), r2 = format(summary(m)$r.squared, digits = 3))) as.character(as.expression(eq)); } p1 <- p … Read more

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative. Start with a subset of the original data: datos <- structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 1317798000, 1317884400, 1317970800, … Read more