`annotate` in `ggplot2` reports errors when combined with `facet_grid` - r

I want to add two annotations to the ggplot graph.
When the graph doesn't contain a facet_grid, such as p1, adding such a annotate layer works fine, i.e., q1. However, when I add a facet_grid layer, to the original graph, i.e., p2, then adding the same 'annotate' layer, i.e., q2 results in an error reporting:
Error: Aesthetics must be either length 1 or the same as the data (4): label
Any suggestion? Thanks.
PS, the version of the package ggplot2 I used is 2.2.1.
p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p2 <- p1 + facet_grid(vs~.)
q1 <- p1 + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))
q2 <- p2 + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))

The following is the answer I got from the package author, Hadley Wickham:
https://github.com/tidyverse/ggplot2/issues/2221
Unfortunately it's very hard to have annotate() do this automatically. Instead just do it "by hand" by creating the dataset yourself.
library(ggplot2)
df <- data.frame(wt = 2:3, mpg = 20:21, label = c("my label", "label 2"))
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
geom_text(aes(label = label), data = df) +
facet_grid(vs ~ .)

The problem is that You used for x= 2:3 and for y=20:21. X and Y should be given only one value/argument and not a vector as in Your case. If You change to x=2 and y=20, then the plot appears without any Error:
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + facet_grid(vs~.) + annotate("text", x = 2, y = 20, label = c("my label", "label 2"))

Related

Add additional labels from a DataFrame to a facet_grid with existing label

I have a set data that I need to add to levels of labels. One on a single chart within the facet grid, and one from a small dataframe with entries for for each chart.
In the example below you'll see that I can add to a single chart no problem but when I try to add from the df I get the error -
Error in FUN(X[[i]], ...) : object 'wt' not found
Preparation:
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_line()
p <- p + facet_grid(. ~ cyl)
ann_text <- data.frame(mpg = 30,wt = 5,lab = "Text",
cyl = factor(8,levels = c("4","6","8")))
dfl <- data.frame(name = c('Jim',"Bob", "Sue"), r = c(-0.2, 0.5, -0.4))
Single Label:
p + geom_text(data = ann_text,label = "Text")
Multiple Labels:
p + geom_text(data = ann_text,label = "Text") +
geom_text(data = dfl, mpg = 30,wt = 5, aes(label = r))
The method I'm using is trying to recreate other examples I've found here on SO and elsewhere but I seem to be missing something.
It's not working in your second code because in the second geom_text, your mpg and wt in not in aes(). Also, these two variables are absent in your dfl.
If you wish to have better control of the labelling of your r variable, you can create extra columns in dfl specifying the x and y location of the label, and use these variables in geom_text(aes()).
Note that I have modified the y position in the second geom_text to avoid overlapping "0,2" with "Text".
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_line()
p <- p + facet_grid(. ~ cyl)
ann_text <- data.frame(mpg = 30,wt = 5,lab = "Text",
cyl = factor(8,levels = c("4","6","8")))
dfl <- data.frame(name = c('Jim',"Bob", "Sue"), r = c(-0.2, 0.5, -0.4))
p + geom_text(data = ann_text,label = "Text") +
geom_text(data = dfl, aes(30, 4, label = r), check_overlap = T)
Created on 2022-05-06 by the reprex package (v2.0.1)

Axis label specifications in ggplot

I'm attempting to have a two-line y-axis label that contains a superscript in ggplot and I am struggling.
I want the y axis label to say “[3H]ASEM binding (pmol/g)” with the 3 superscripted and (pmol/g) on a separate line.
This is what I have tried so far:
labs(x="", y=expression(paste("[" ^3 "H] ASEM Binding \n (pmol/g)")))
And it's given me the error "unexpected string constant"
Any suggestions?
You need an empty ''(2 single quotes) prior to the ^3.
ggplot(sample_data, aes(x, y)) +
geom_point() +
labs(
x = "",
y = expression(atop(paste("[", ''^3, "H] ASEM Binding"), "(pmol/g)"))
)
Another alternative is:
y = expression(atop("["^3*"H] ASEM Binding", "(pmol/g)"))
I'm not quite sure what you're doing with your for loop, but this code chunk should get you the two-lined axis label with a superscript for which you are looking.
library(tidyverse)
sample_data <- tibble(x = rnorm(1000),
y = x^2)
sample_data %>%
ggplot(aes(x, y)) +
geom_point() +
labs(
x = "X",
y = expression(atop("Variable", X^2))
)
Is this what you are after?
library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point()+
labs(x = "",
y = expression(atop("[ "^3*H~"] ASEM Binding", "(pmol/g)")))+
theme(plot.margin = unit(c(10, 10, 20, 10), "mm"))
Created on 2020-05-19 by the reprex package (v0.3.0)

Display Greek symbols and charge facet titles at the same time with ggplot

I know how to modify titles in ggplot without altering the original data. Suppose I have the following data frame and I want to change the labels. Then, I would do so in the following way
df <- data.frame(x = 1:4, y = 1:4, label = c(c("params[1]", "params[2]", "params[3]",
"params[4]")))
params_names <- list(
'params[1]'= "beta[11]",
'params[2]'= "beta[22]",
'params[3]'= "beta[33]",
'params[4]'= "beta[44]"
)
param_labeller <- function(variable, value){
params_names[value]
}
ggplot(df, aes(x=x,y=y)) +
geom_point() +
facet_grid(~label, labeller = param_labeller)
If I wanted to display the subscripts, I would just do this
ggplot(df, aes(x=x,y=y)) +
geom_point() +
facet_grid(~label, labeller = label_parsed)
How do I apply both operations at the same time?
I don't know exactly if this conflicts with you not wanting to "alter" the original data, but you add the labelling information to the factor itself:
df$label2 <- factor(df$label,
labels = c("beta[4]", "beta[24]", "beta[42]", "beta[43]"))
ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_grid( ~ label2, labeller = label_parsed)
This produces the following plot:
Plot with formatted facet labels

How to add different lines for facets

I have data where I look at the difference in growth between a monoculture and a mixed culture for two different species. Additionally, I made a graph to make my data clear.
I want a barplot with error bars, the whole dataset is of course bigger, but for this graph this is the data.frame with the means for the barplot.
plant species means
Mixed culture Elytrigia 0.886625
Monoculture Elytrigia 1.022667
Monoculture Festuca 0.314375
Mixed culture Festuca 0.078125
With this data I made a graph in ggplot2, where plant is on the x-axis and means on the y-axis, and I used a facet to divide the species.
This is my code:
limits <- aes(ymax = meansS$means + eS$se, ymin=meansS$means - eS$se)
dodge <- position_dodge(width=0.9)
myplot <- ggplot(data=meansS, aes(x=plant, y=means, fill=plant)) + facet_grid(. ~ species)
myplot <- myplot + geom_bar(position=dodge) + geom_errorbar(limits, position=dodge, width=0.25)
myplot <- myplot + scale_fill_manual(values=c("#6495ED","#FF7F50"))
myplot <- myplot + labs(x = "Plant treatment", y = "Shoot biomass (gr)")
myplot <- myplot + opts(title="Plant competition")
myplot <- myplot + opts(legend.position = "none")
myplot <- myplot + opts(panel.grid.minor=theme_blank(), panel.grid.major=theme_blank())
So far it is fine. However, I want to add two different horizontal lines in the two facets. For that, I used this code:
hline.data <- data.frame(z = c(0.511,0.157), species = c("Elytrigia","Festuca"))
myplot <- myplot + geom_hline(aes(yintercept = z), hline.data)
However if I do that, I get a plot were there are two extra facets, where the two horizontal lines are plotted. Instead, I want the horizontal lines to be plotted in the facets with the bars, not to make two new facets. Anyone a idea how to solve this.
I think it makes it clearer if I put the graph I create now:
Make sure that the variable species is identical in both datasets. If it a factor in one on them, then it must be a factor in the other too
library(ggplot2)
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10))
dummy1$D <- rnorm(nrow(dummy1))
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0))
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) +
geom_hline(data = dummy2, aes(yintercept = Z))
dummy2$X <- factor(dummy2$X)
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) +
geom_hline(data = dummy2, aes(yintercept = Z))

how to add labels to a plot

Is there a way to add labels to each point in a plot? I did this on an image editor just to convey the idea: 1.
The original one was generated with:
qplot(pcomments, gcomments , data = topbtw, colour = username)
To follow up on Andrie's excellent answer, I frequently employ two methods to add labels to a subset of points on a plot if I need to highlight specific data. Both are demonstrated below:
dat <- data.frame(x = rnorm(10), y = rnorm(10), label = letters[1:10])
#Create a subset of data that you want to label. Here we label points a - e
labeled.dat <- dat[dat$label %in% letters[1:5] ,]
ggplot(dat, aes(x,y)) + geom_point() +
geom_text(data = labeled.dat, aes(x,y, label = label), hjust = 2)
#Or add a separate layer for each point you want to label.
ggplot(dat, aes(x,y)) + geom_point() +
geom_text(data = dat[dat$label == "c" ,], aes(x,y, label = label), hjust = 2) +
geom_text(data = dat[dat$label == "g" ,], aes(x,y, label = label), hjust = 2)
Yes, use geom_text() to add text to your plot. Here is an example:
library(ggplot2)
qplot(mtcars$wt, mtcars$mpg, label=rownames(mtcars), geom="text")
ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars))) + geom_text(size=3)
See the on-line documentation for more information: http://had.co.nz/ggplot2/geom_text.html

Resources