I use ggplot to make most of my graphics. These can be single panels, or faceted. To make it easier to track revisions, I would like to generate a small label in the corner of the plot that includes some text.
In pseudo code, I am looking for something like this:
# generate the initial plot
p <- ggplot()
# add the label
p + someAnnotationFunction(label = "Version 1.0", x = 1, y = 0,
hjust = "right", vjust = "bottom" )
# print
print(p)
Or: plot my label nestled in the lower right corner of my figure without messing up the existing ggplot graphics.
So far I'm not having any luck finding a solution. This (very interesting) method doesn't work if you have a full m x n table of facets. Methods using gridExtra tend to mess with the plots too much. So, does anyone have a way to add arbitrary text anywhere on a plot that was generated using ggplot?
Here's a worked solution using gridExtra(), based on Baptiste's comment:
require("ggplot2")
require("gridExtra")
# set our working directory
working.dir <- '/Users/aclifton/Documents/projects/Rcode'
setwd(working.dir)
# create a data frame
df <- data.frame(x =runif(100, 1, 10),
y = runif(100, 1, 10))
#create a plot
p <- ggplot(data = df,
aes(x = x,
y = y)) +
geom_point()
print(p)
We now have our plot, and the trick is adding that label and saving the overall plot using ggsave():
# label to show
sub.label = textGrob("Some kind of label",
gp=gpar(fontsize=6),
x = unit(1, "npc"),
hjust = 1,
vjust = 0)
ggsave(filename=file.path(working.dir,'DemoPlot.png'),
plot = arrangeGrob(p,
sub = sub.label,
clip = FALSE),
scale = 1,
width = 6.5,
height = 3.5,
units = c("in"),
dpi = 300)
Which gives you this:
By making a data frame of your annotations, you can add them on top of your plot using geom_text.
note <- data.frame(xVarName = c(1, 5), yVarName = c(1, 10),
text = c("Version 1.0", "April 26, 2014")
p + geom_text(data = anno, aes(label = text))
"Version 1.0" will show up in the bottom left and "April 26, 2014" will show up in the top right.
By making your notes in a separate dataframe, you can add multiple notes to one graph if desired.
Related
I am trying to arrange two ggplot2 plots side by side, i.e., in a two-column
layout using the package gridExtra. I am interested in ensuring that both
plots have equal plotting area (i.e., the gray plot panel is the same for both
plots) regardless of the height of the x-axis labels. As you can see in the
example below, when longer x-axis labels are used, gridExtra::grid.arrange()
seems to compensate this by adjusting the plotting area (i.e., the grayed out
part of the plot).
# Dummy data.
data <- data.frame(x = 1:10, y = rnorm(10))
# Dummy labels.
x_labels_short <- 1:10
x_labels_long <- 100001:100010
# Common settings for both `ggplot2` plots.
layers <- list(
labs(
x = "Plot title"
),
theme(
axis.text.x = element_text(
angle = 90,
vjust = 0.5,
hjust = 1
)
)
)
# `ggplot2 plot (a).
plot_a <- ggplot(data, aes(x, y)) +
scale_x_continuous(breaks = 1:10, labels = x_labels_short) +
layers
# `ggplo2` plot (b).
plot_b <- ggplot(data, aes(x, y)) +
scale_x_continuous(breaks = 1:10, labels = x_labels_long) +
layers
# Showing the plots side by side.
gridExtra::grid.arrange(
plot_a,
plot_b,
ncol = 2
)
Output:
What I want is for both plots to (1) have equal plotting area and (b) the x-axis
title of plot_a to be aligned with that of plot_b (i.e., the x-axis title of
plot_a to be offset based on the length of of the x-axis labels of plot_b).
If this is not clear, this is what I want to achieve would look like with base
R.
# Wrapper for convenience.
plot_gen <- function(data, labels) {
plot(
NULL,
xlim = c(1, 10),
ylim = c(min(data$y), max(data$y)),
xlab = "",
ylab = "y",
xaxt = "n"
)
axis(
side = 1,
at = 1:10,
labels = labels,
las = 2
)
title(
xlab = "Plot title",
line = 4.5
)
}
# Get `par`.
old_par = par(no.readonly = TRUE)
# Set the two-column layout.
layout(matrix(1:2, ncol = 2))
# Adjust margins.
par(mar = old_par$mar + c(1.5, 0, 0, 0))
# Plot base plot one.
plot_gen(data, x_labels_short)
# Plot base plot two.
plot_gen(data, x_labels_long)
# Restore `par`.
par(old_par)
# Restore layout.
layout(1:1)
Output:
Quick mention. I found a similar question on SO (i.e.,
How to specify the size of a graph in ggplot2 independent of axis labels), however I fail to see how the
answers address the problem. Also, the plots I am trying to arrange are based
on different data and I don't think I can use a facet_wrap approach.
One suggestion: the patchwork package.
library(patchwork)
plot_a + plot_b
It also works for more complex layouts, e.g.:
(plot_a | plot_b) / plot_a
I have a grid composed of several ggplots and want to add an x axis, where axis ticks and annotations are added between the plots. I could not came up with a better solution than to create a custom plot for the axis and adding it below with arrangeGrob. But they do not align with the plots (I draw arrows where the numbers should be). Also there is a large white space below which I don't want.
I will also need an analogue for the y-axis.
library(ggplot2)
library(gridExtra)
library(ggpubr)
library(grid)
# Create a grid with several ggplots
p <-
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
theme_transparent() +
theme(plot.background = element_rect(color = "black"))
main.plot <- arrangeGrob(p, p, p, p, p, p, p, p, ncol = 4, nrow = 2)
# grid.draw(main.plot)
# Now add an x axis to the main plot
x.breaks <- c(0, 1, 2.5, 8, 10)
p.axis <- ggplot() +
ylim(-0.1, 0) +
xlim(1, length(x.breaks)) +
ggpubr::theme_transparent()
for (i in seq_along(x.breaks)) {
p.axis <- p.axis +
geom_text(aes_(x = i, y = -0.01, label = as.character(x.breaks[i])), color = "red")
}
# p.axis
final.plot <- arrangeGrob(main.plot, p.axis, nrow = 2)
grid.draw(final.plot)
Any help appreciated.
Note: In the code below, I assume each plot in your grid has equal width / height, & used equally spaced label positions. If that's not the case, you'll have to adjust the positions yourself.
Adding x-axis to main.plot:
library(gtable)
# create additional row below main plot
# height may vary, depending on your actual plot dimensions
main.plot.x <- gtable_add_rows(main.plot, heights = unit(20, "points"))
# optional: check results to verify position of the new row
dev.off(); gtable_show_layout(main.plot.x)
# create x-axis labels as a text grob
x.axis.grob <- textGrob(label = x.breaks,
x = unit(seq(0, 1, length.out = length(x.breaks)), "npc"),
y = unit(0.75, "npc"),
just = "top")
# insert text grob
main.plot.x <- gtable_add_grob(main.plot.x,
x.axis.grob,
t = nrow(main.plot.x),
l = 1,
r = ncol(main.plot.x),
clip = "off")
# check results
dev.off(); grid.draw(main.plot.x)
You can do the same for the y-axis:
# create additional col
main.plot.xy <- gtable_add_cols(main.plot.x, widths = unit(20, "points"), pos = 0)
# create y-axis labels as a text grob
y.breaks <- c("a", "b", "c") # placeholder, since this wasn't specified in the question
y.axis.grob <- textGrob(label = y.breaks,
x = unit(0.75, "npc"),
y = unit(seq(0, 1, length.out = length(y.breaks)), "npc"),
just = "right")
# add text grob into main plot's gtable
main.plot.xy <- gtable_add_grob(main.plot.xy,
y.axis.grob,
t = 1,
l = 1,
b = nrow(main.plot.xy) - 1,
clip = "off")
# check results
dev.off(); grid.draw(main.plot.xy)
(Note that the above order of x-axis followed by y-axis should not be switched blindly. If you are adding rows / columns, it's good habit to use gtable_show_layout() frequently to check the latest gtable object dimensions, & ensure that you are inserting new grobs into the right cells.)
Finally, let's add some buffer on all sides, so that the labels & plot borders don't get cut off:
final.plot <- gtable_add_padding(main.plot.xy,
padding = unit(20, "points"))
dev.off(); grid.draw(final.plot)
I am trying to add the file name outside a plot area obtained with ggplot, using facet_wrap. I was pretty sure I found the solution in this post:
Add filename or other annotation to ggplot figures. However, applying the solution to my problem gives a distorted image.
The code to generate this is here:
require("gridExtra")
library(tidyverse)
df <- data.frame(x =runif(100, 1, 10),
y = runif(100, 1, 10),
myfacet = c("one", "two"))
p <- ggplot(data = df,
aes(x = x,
y = y)) +
geom_point() +
facet_wrap(~myfacet)
print(p)
script.name <- "myscript.R"
sub.label = textGrob(script.name,
gp=gpar(fontsize=6),
x = unit(1, "npc"),
hjust = 1,
vjust = 1)
ggsave(filename="../plots/myplot.png",
plot = arrangeGrob(p,
sub = sub.label,
clip = FALSE))
If I just use
ggsave(filename="../plots/myplot2.png",
plot = p)
I get the following image:
Please note that I need a solution that works outside the facets.
Could anyone provide a hint as to what is going on? Thank you!
grid.arrange(p, bottom = sub.label)
I'm trying to convert my ggplot to a plotly plot using ggplotly(). However, it doesn't seem to work on this code, after manipulate is acted on the plot. Is there any other way to do it?
library(ggplot2)
library(manipulate)
grades <- data.frame(Final = 20 * runif(70))
myFinalsPlot <- function(sliderInput, initialIndex, finalIndex) {
ggplot(data.frame(grades$Final[initialIndex:finalIndex]),
aes(x = grades$Final[initialIndex:finalIndex])) +
geom_histogram(aes(y = ..density..),
binwidth = sliderInput, colour = "green", fill = "yellow") +
geom_density(alpha = 0.2, fill = "#FF6666") +
labs(x = "Marks", y = "Grades")
}
myFinalsPlot <- manipulate(myFinalsPlot(slidersInput, 1, 70),
slidersInput = slider(1, 12, step = 1, initial = 5))
First, to make your code work with the ggplot2 plot, there is an issue in your code that you need to fix. You shouldn't give the same name to your function and plot object. Replace this:
myFinalsPlot <- manipulate(myFinalsPlot(slidersInput, 1, 70),
slidersInput = slider(1, 12, step = 1, initial = 5))
By, e.g.:
myPlot <- manipulate(myFinalsPlot(slidersInput, 1, 70),
slidersInput = slider(1, 12, step = 1, initial = 5))
Now, regarding plotly plots, I don't think it is supposed to work with manipulate. I quote RStudio's website https://support.rstudio.com/hc/en-us/articles/200551906-Interactive-Plotting-with-Manipulate:
RStudio works with the manipulate package to add interactive capabilities to standard R plots.
I'm trying to create a figure similar to the one below (taken from Ro, Russell, & Lavie, 2001). In their graph, they are plotting bars for the errors (i.e., accuracy) within the reaction time bars. Basically, what I am looking for is a way to plot bars within bars.
I know there are several challenges with creating a graph like this. First, Hadley points out that it is not possible to create a graph with two scales in ggplot2 because those graphs are fundamentally flawed (see Plot with 2 y axes, one y axis on the left, and another y axis on the right)
Nonetheless, the graph with superimposed bars seems to solve this dual sclaing problem, and I'm trying to figure out a way to create it in R. Any help would be appreciated.
It's fairly easy in base R, by using par(new = T) to add to an existing graph
set.seed(54321) # for reproducibility
data.1 <- sample(1000:2000, 10)
data.2 <- sample(seq(0, 5, 0.1), 10)
# Use xpd = F to avoid plotting the bars below the axis
barplot(data.1, las = 1, col = "black", ylim = c(500, 3000), xpd = F)
par(new = T)
# Plot the new data with a different ylim, but don't plot the axis
barplot(data.2, las = 1, col = "white", ylim = c(0, 30), yaxt = "n")
# Add the axis on the right
axis(4, las = 1)
It is pretty easy to make the bars in ggplot. Here is some example code. No two y-axes though (although look here for a way to do that too).
library(ggplot2)
data.1 <- sample(1000:2000, 10)
data.2 <- sample(500:1000, 10)
library(ggplot2)
ggplot(mapping = aes(x, y)) +
geom_bar(data = data.frame(x = 1:10, y = data.1), width = 0.8, stat = 'identity') +
geom_bar(data = data.frame(x = 1:10, y = data.2), width = 0.4, stat = 'identity', fill = 'white') +
theme_classic() + scale_y_continuous(expand = c(0, 0))