Reputation: 1516
Data file is way to big to dput
but I am hoping that somebody will be able to identify my error. Here is the story: I produced the following small multiples plot using ggplot with the following code. Everything is working just fine.
ggplot(sm.df, aes(year, N, group = 1)) + geom_line(aes(colour = top10)) +
facet_wrap( ~ shortTitle, ncol=7) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x = element_text(angle=45, hjust=1, size =8)) +
scale_x_discrete(breaks=seq(1989, 2020, 8)) +
ylim(0, 150)
Now, I want to annotate each facet with the overall N. I created a vector containing the x position, y position, and the actual values to be plotted. So, basically, everything will be in the same X and Y position on every plot, with a different label.
'data.frame': 78 obs. of 3 variables:
$ x1 : num 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 ...
$ y1 : num 130 130 130 130 130 130 130 130 130 130 ...
$ N.label: int 1650 1456 1348 1216 1086 1035 985 940 888 826 ...
But, when I add geom_text(data = x.df, aes(x = x1, y = y1, label = N.label), inheret.aes=FALSE)
to the plot, it appears as though every label is being reprinted on every facet. Obviously I am doing something wrong.
I have poured through SO on how to annotate faceted plots, but I am missing this problem. Would be greatly appreciated if you have any ideas -- not very straightforward to produce some data, but I guess I will if I need to.
Upvotes: 1
Views: 2472
Reputation: 1621
This answer to a very similar question should help. There needs to be an identifier that identifies which facet to print which label on. In your case, you should use shortTitle
for the purpose.
This is a modified example using mtcars
and both faceting and labeling according to the number of gears
library(ggplot2)
xpos <- c(10,10,10)
ypos <- c(Inf,Inf,Inf)
lab <- c(378,2,50)
gears <- c(3:5)
ldata <- data.frame(xpos, ypos, lab, gears)
ggplot(mtcars) + geom_bar(aes(x=cyl)) + facet_wrap(~gears, ncol=2) +
geom_text(data=ldata, aes(x=xpos, y=ypos,
label=lab, size=1),
vjust=2, parse=FALSE)
Try adding shortTitle
to your list of labels. It looks like that may be all you need. If you provide a subsample of your data frame, this would help to be sure.
Upvotes: 4