ggplot2 - custom grob over axis lines - r

I'm trying to generate an axis line break in ggplot2 (with a white segment over the axis lines) and I'm having some trouble.
Using the informative post annotate-ggplot-with-an-extra-tick-and-label I was able to generate the custom grobs in given location, while also turning the panel off to "draw" outside of the plotting area.
I'm also familiar with other packages such as plotrix and am able to replicate broken axis in base, but more than anything I'm interested in learning why the axis grobs I'm creating aren't overwriting the line. Here is some sample code:
library(ggplot2) # devtools::install_github("hadley/ggplot2")
library(grid)
library(scales)
data("economics_long")
econ <- economics_long
econ$value01 <- (econ$value01/2)
x <- ggplot(econ, aes(date, value01,group=1)) + scale_y_continuous(labels=c(0.0,0.1,0.2,0.3,0.4,0.5,1.0), breaks=c(0.0,0.1,0.2,0.3,0.4,0.5,0.6),limits = c(0,.6),expand = c(0, 0)) +
geom_smooth(colour="deepskyblue", show.legend = TRUE ) + theme_bw()
theme_white <- theme(panel.background=element_blank(),
panel.border=element_rect(color="white"),
plot.margin = unit(c(.2, 0, .2, .2), "cm"),
panel.grid.major.y=element_blank(),
panel.grid.major.x=element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.minor.y=element_blank(),
axis.title.y = element_blank(),
axis.line.x=element_line(color="gray", size=1),
axis.line.y=element_line(color="gray", size=1),
axis.text.x=element_text(size=12),
axis.text.y=element_text(size=12),
axis.ticks=element_line(color="gray", size=1),
legend.position="none"
)
x <- x + theme_white
gline = linesGrob(y = c(0, 1.5),x = c(-.015, .015), gp = gpar(col = "black", lwd = 2.5))
gline2 = linesGrob(y = c(-0.25, 0.5),x = c(0, 0), gp = gpar(col = "red", lwd = 5))
p = x + annotation_custom(gline, ymin=.55, ymax=.575, xmin=-Inf, xmax=Inf) +
annotation_custom(gline, ymin=.525, ymax=.55, xmin=-Inf, xmax=Inf) +
annotation_custom(gline2, ymin=.55, ymax=.575, xmin=-Inf, xmax=Inf)
# grobs are placed under the axis lines....
g = ggplotGrob(p)
g$layout$clip[g$layout$name=="panel"] <- "off"
grid.draw(g)
Which creates this image:
I'm curious why the annotation_custom grobs are placed under the axis lines and whether there is a better solution to adding custom grobs using ggplot2. There appears to be an order in which graphics are placed in the plotting windows - how might this be alternated so that the custom grobs are placed after the axis lines?

You were close. The layout data frame is were you turned off clipping. There is another column in the layout data frame that gives the order in which the various plot elements are drawn - z. The plot panel (including the annotation) is drawn second (after the background), then later the axes are drawn. Change the value of z for the plot panel to something larger than the z values for the axes.
library(ggplot2) # devtools::install_github("hadley/ggplot2")
library(grid)
library(scales)
data("economics_long")
econ <- economics_long
econ$value01 <- (econ$value01/2)
x <- ggplot(econ, aes(date, value01,group=1)) + scale_y_continuous(labels=c(0.0,0.1,0.2,0.3,0.4,0.5,1.0), breaks=c(0.0,0.1,0.2,0.3,0.4,0.5,0.6),limits = c(0,.6),expand = c(0, 0)) +
geom_smooth(colour="deepskyblue", show.legend = TRUE ) + theme_bw()
theme_white <- theme(panel.background=element_blank(),
panel.border=element_rect(color="transparent"),
plot.margin = unit(c(.2, 0, .2, .2), "cm"),
panel.grid.major.y=element_blank(),
panel.grid.major.x=element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.minor.y=element_blank(),
axis.title.y = element_blank(),
axis.line.x=element_line(color="gray", size=1),
axis.line.y=element_line(color="gray", size=1),
axis.text.x=element_text(size=12),
axis.text.y=element_text(size=12),
axis.ticks=element_line(color="gray", size=1),
legend.position="none"
)
x <- x + theme_white
gline = linesGrob(y = c(0, 1.5),x = c(-.015, .015), gp = gpar(col = "black", lwd = 2.5))
gline2 = linesGrob(y = c(-0.25, 0.5),x = c(0, 0), gp = gpar(col = "red", lwd = 5))
p = x + annotation_custom(gline, ymin=.55, ymax=.575, xmin=-Inf, xmax=Inf) +
annotation_custom(gline, ymin=.525, ymax=.55, xmin=-Inf, xmax=Inf) +
annotation_custom(gline2, ymin=.55, ymax=.575, xmin=-Inf, xmax=Inf)
# grobs are placed under the axis lines....
g = ggplotGrob(p)
g$layout$clip[g$layout$name=="panel"] <- "off"
g$layout # Note that z for panel is 1. Change it to something bigger.
g$layout$z[g$layout$name=="panel"] = 17
grid.newpage()
grid.draw(g)

Related

Plot title is not displaying on two lines while using conventional methods [duplicate]

I'm using ggplot2 to improve precipitation barplots.
Here's a reproducible example of what I want to achieve:
library(ggplot2)
library(gridExtra)
secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])
m <- ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
opts(axis.text.x=theme_text(angle=-45, hjust=0, vjust=1),
title=expression("Rainfall"), plot.margin = unit(c(1.5, 1, 1, 1), "cm"),
plot.title = theme_text(size = 25, face = "bold", colour = "black", vjust = 5))
z <- arrangeGrob(m, sub = textGrob("Location", x = 0, hjust = -3.5, vjust = -33, gp = gpar(fontsize = 18, col = "gray40"))) #Or guessing x and y with just option
z
I don't know how to avoid using guessing numbers on hjust and vjust on ggplot2? Is there a better way to put a subtitle (not just using \n, but a subtitle with different text color and size)?
I need to be able to use with ggsave to have a pdf file.
Here are two related questions:
Add a footnote citation outside of plot area in R?
How can I add a subtitle and change the font size of ggplot plots in R?
Thanks for any help.
The latest ggplot2 builds (i.e., 2.1.0.9000 or newer) have subtitles and below-plot captions as built-in functionality. That means you can do this:
library(ggplot2) # 2.1.0.9000+
secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])
m <- ggplot(melt.d, aes(x=x, y=y))
m <- m + geom_bar(fill="darkblue", stat="identity")
m <- m + labs(x="Weather stations",
y="Accumulated Rainfall [mm]",
title="Rainfall",
subtitle="Location")
m <- m + theme(axis.text.x=element_text(angle=-45, hjust=0, vjust=1))
m <- m + theme(plot.title=element_text(size=25, hjust=0.5, face="bold", colour="maroon", vjust=-1))
m <- m + theme(plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="black"))
m
Ignore this answer ggplot2 version 2.2.0 has title and subtitle functionality. See #hrbrmstr's answer below.
You could use nested atop functions inside an expression to get different sizes.
EDIT Updated code for ggplot2 0.9.3
m <- ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
ggtitle(expression(atop("Rainfall", atop(italic("Location"), "")))) +
theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1),
#plot.margin = unit(c(1.5, 1, 1, 1), "cm"),
plot.title = element_text(size = 25, face = "bold", colour = "black", vjust = -1))
it's not too hard to add grobs to the gtable and make a fancy title that way,
library(ggplot2)
library(grid)
library(gridExtra)
library(magrittr)
library(gtable)
p <- ggplot() +
theme(plot.margin = unit(c(0.5, 1, 1, 1), "cm"))
lg <- list(textGrob("Rainfall", x=0, hjust=0,
gp = gpar(fontsize=24, fontfamily="Skia", face=2, col="turquoise4")),
textGrob("location", x=0, hjust=0,
gp = gpar(fontsize=14, fontfamily="Zapfino", fontface=3, col="violetred1")),
pointsGrob(pch=21, gp=gpar(col=NA, cex=0.5,fill="steelblue")))
margin <- unit(0.2, "line")
tg <- arrangeGrob(grobs=lg, layout_matrix=matrix(c(1,2,3,3), ncol=2),
widths = unit.c(grobWidth(lg[[1]]), unit(1,"null")),
heights = do.call(unit.c, lapply(lg[c(1,2)], grobHeight)) + margin)
grid.newpage()
ggplotGrob(p) %>%
gtable_add_rows(sum(tg$heights), 0) %>%
gtable_add_grob(grobs=tg, t = 1, l = 4) %>%
grid.draw()
It appears opts is deprecated as of ggplot 2 0.9.1 and no longer functional. This worked for me with the latest versions as of today: + ggtitle(expression(atop("Top line", atop(italic("2nd line"), "")))).
This version uses a gtable function. It allows two lines of text in the title. The text, size, colour, and font face of each line can be set independently of the other. However, the function will modify a plot with a single plot panel only.
Minor edit: Updating to ggplot2 v2.0.0
# The original plot
library(ggplot2)
secu <- seq(1, 16, by = 2)
melt.d <- data.frame(y = secu, x = LETTERS[1:8])
m <- ggplot(melt.d, aes(x = x, y = y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x = "Weather stations", y = "Accumulated Rainfall [mm]") +
theme(axis.text.x = element_text(angle = -45, hjust = 0, vjust = 1))
# The function to set text, size, colour, and face
plot.title = function(plot = NULL, text.1 = NULL, text.2 = NULL,
size.1 = 12, size.2 = 12,
col.1 = "black", col.2 = "black",
face.1 = "plain", face.2 = "plain") {
library(gtable)
library(grid)
gt = ggplotGrob(plot)
text.grob1 = textGrob(text.1, y = unit(.45, "npc"),
gp = gpar(fontsize = size.1, col = col.1, fontface = face.1))
text.grob2 = textGrob(text.2, y = unit(.65, "npc"),
gp = gpar(fontsize = size.2, col = col.2, fontface = face.2))
text = matrix(list(text.grob1, text.grob2), nrow = 2)
text = gtable_matrix(name = "title", grobs = text,
widths = unit(1, "null"),
heights = unit.c(unit(1.1, "grobheight", text.grob1) + unit(0.5, "lines"), unit(1.1, "grobheight", text.grob2) + unit(0.5, "lines")))
gt = gtable_add_grob(gt, text, t = 2, l = 4)
gt$heights[2] = sum(text$heights)
class(gt) = c("Title", class(gt))
gt
}
# A print method for the plot
print.Title <- function(x) {
grid.newpage()
grid.draw(x)
}
# Try it out - modify the original plot
p = plot.title(m, "Rainfall", "Location",
size.1 = 20, size.2 = 15,
col.1 = "red", col.2 = "blue",
face.2 = "italic")
p
You could use wrap the plot in grid.arrange and pass a custom grid-based title,
library(ggplot2)
library(gridExtra)
p <- ggplot() +
theme(plot.margin = unit(c(0.5, 1, 1, 1), "cm"))
tg <- grobTree(textGrob("Rainfall", y=1, vjust=1, gp = gpar(fontsize=25, face=2, col="black")),
textGrob("location", y=0, vjust=0, gp = gpar(fontsize=12, face=3, col="grey50")),
cl="titlegrob")
heightDetails.titlegrob <- function(x) do.call(sum,lapply(x$children, grobHeight))
grid.arrange(p, top = tg)
You might have noticed that Sandy's code doesn't produce a bold title for "Rainfall" - the instruction to make this bold should occur within the atop() function rather than the theme() function.
ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
ggtitle(expression(atop(bold("Rainfall"), atop(italic("Location"), "")))) +
theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1),
plot.title = element_text(size = 25, colour = "black", vjust = -1))

Add a customized x-axis to plot ggplot2 and y-axis as well

I have the following code:
df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),
roi=rep(1:10,10),
area=runif(100, 5.0, 7.5))
df$time=factor(df$time, levels=rev(levels(df$time)))
ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() + coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1) +
scale_fill_gradient(low="black",high="white")
Now, I want to remove the x-axis and add a new one to have the expected fig below. The x-axis will be divided into 4 parts for 4 segs with 39%,23%,23%,15% of axis length for Seg 1, Seg 2, Seg 3, Seg 4, respectively. Could anybody hava any idea to solve it. I apprecicate all response and am looking forward your answers.
Great thanks to Mark Heckmann for helpful answer to my problem. I would like to ask one more thing. I also want to modify the y-axis by "scale_y_discrete", the code ran well but the y-axis label did not meet my expectation. The code I ran is:
ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) + theme_minimal() +coord_fixed(ratio=1) +geom_tile(colour = NA, width = 1.5, height = 1)+scale_fill_gradient(low="black",high="white") +scale_y_discrete(name="Time (min)",expand =c(0.01,0.1),breaks=c(1,2.5,5.0,7.5,10.0),labels=c(0,15,30,45,60))
Thank you very much!
You need to use annotation_custom to draw outside the plotting area.
#### your plot
library(ggplot2)
g <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() + coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1) +
scale_fill_gradient(low="black",high="white")
Extra code:
library(grid)
# remove axis
g <- g + theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
scale_x_discrete(expand = c(0,0))
# calculate segment coordinates
segs <- c(.39, .23, .23, .15)
segs_center <- cumsum(segs) - segs/2
seg_ticks <- cumsum(segs)[1:3]
seg_labels <- paste("Seg", seq_along(segs))
# create graphicaal objects and gather as tree
grobs <- grobTree(linesGrob(c(0,1), c(.5,.5)),
segmentsGrob(x0=seg_ticks, x1=seg_ticks, y0=0, y1=1),
textGrob(x=segs_center, y=0,
label = seg_labels, hjust = .5, gp = gpar(cex =.7)))
# insert grobsTree in as annotation
g <- g + annotation_custom( grob = grobs,
ymin = -.2, ymax = .2,
xmin = .25, xmax = 10.75)
# override clipping for plotting outside of plotting area
gt <- ggplot_gtable(ggplot_build(g))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.newpage()
grid.draw(gt)
This is as good as I can get without going into custom annotation grobs.
library(ggplot2)
library(grid)
df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),
roi=rep(1:10,10),area=runif(100, 5.0, 7.5))
df$time=factor(df$time, levels=rev(levels(df$time)))
p1 <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() +coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1)+
scale_fill_gradient(low="black",high="white") +
scale_x_discrete(breaks = c(4,6,8,10),
labels = paste0("Seg",1:4)) +
theme(axis.title.x = element_blank(),
axis.ticks.x = element_line(size =1),
axis.text.x = element_text(hjust=c(2,1.5,1.5,1.5)),
plot.margin = unit(c(2,0,2,0), "lines"))
See here if you want to look into drawing the axis labels and tick marks customwise.

R: ggplot slight adjustment for clustering summary

Please check my reproducible example and the result chart.
X = t(USArrests)
plot_color_clust = function(X,N=N,
cols=c("red","blue", "orange", "darkgreen","green","yellow","grey","black","white")
){
library(ggplot2)
library(gridExtra)
library(gtable)
library(scales)
library(ggdendro)
library(grid)
library(plyr)
if(N>length(cols)) stop("N too big. Not enough colors in cols.")
if(N>ncol(X)) stop("N too big. Not enough columns in data.")
fit = ClustOfVar::hclustvar(X.quanti = X)
dd.row = as.dendrogram(fit)
ddata_x <- dendro_data(dd.row)
temp = cutree(fit,k=N)
lab <- ggdendro::label(ddata_x)
x=c()
for(i in 1:nrow(lab)){
x[i]= paste( "clust", as.vector(temp[ lab$label[i]==names(temp) ]) ,sep="")
}
lab$group <- x
p1 <- ggplot(segment(ddata_x)) +
geom_segment(aes(x=x, y=y, xend=xend, yend=yend))+coord_flip()+
geom_text(data=lab,
aes(label=label, x=x, y=0, colour=group),hjust=1) +
theme(legend.position="none",
axis.title.y=element_blank(),
axis.title.x=element_blank(),
axis.text.x = element_text(angle = 0, hjust = 0),
axis.title.x = element_text(angle = 0, hjust = 0))+
theme(axis.text = element_blank(), axis.title = element_blank(),
axis.ticks = element_blank(), axis.ticks.margin = unit(0, "lines"),
axis.ticks.length = unit(0, "cm"))+
scale_colour_manual(values=cols)+coord_flip()+
scale_y_continuous(limits = c(-0.1, 2.1))
df2<-data.frame(cluster=cutree(fit,N),states=factor(fit$labels,levels=fit$labels[fit$order]))
df3<-ddply(df2,.(cluster),summarise,pos=mean(as.numeric(states)))
p2 = ggplot(df2,aes(states,y=1,fill=factor(cluster)))+geom_tile()+
scale_y_continuous(expand=c(0,0))+
theme(axis.title=element_blank(),
axis.ticks=element_blank(),
axis.text=element_blank(),
legend.position="none")+coord_flip()+
geom_text(data=df3,aes(x=pos,label=cluster))+
scale_fill_manual(name = "This is my title", values = cols)
gp1<-ggplotGrob(p1)
gp2<-ggplotGrob(p2)
maxHeight = grid::unit.pmax(gp1$heights[2:5], gp2$heights[2:5])
gp1$heights[2:5] <- as.list(maxHeight)
gp2$heights[2:5] <- as.list(maxHeight)
#grid.arrange(gp2, gp1, ncol=2,widths=c(1/6,5/6))
R = arrangeGrob(gp2,gp1,ncol=2,widths=c(1/6,5/6))
R
}
plot_color_clust(X,6)
Questions:
These two parts (left colors tiles and right clustering tree) has inconsistent heights. How do we adjust their heights for them to match each other's?
How can we make the tree on the right side shorter so states names (clustered subjects) can have more space to be fully displayed?
Is there a way make the white space between those two parts smaller?
Your tweaking of the code is appreciated. Thanks.
One major change: Rather than matching heights of the two charts, I extract the plot panel from gp2, then insert it into column 2 of gp1. There are no margins surrounding the resultant gp2, and thus, partly takes care of your point 3.
With respect to point 2: expand the limits of the axis to make room of the labels. (See point 2. in the code below). The parameters for points 2 and 3 were set by trial-and-error. Adjusting one parameter means the other needs to be adjusted.
With respect to point 1: expand the axis using the additive component of exapnd to add half a unit to each end of the axis (See point 1. in the code below).
Minor edit: updating to ggplot2 2.2.0 and R 3.3.2
axis.ticks.margin is deprecated
X = t(USArrests)
plot_color_clust = function(X, N = N,
# cols=c("red","blue", "orange", "darkgreen","green","yellow","grey","black","white")
cols = rainbow(N) # Easier to pick colours
){
library(ggplot2)
library(gtable)
library(grid)
library(ggdendro)
library(plyr)
if(N > length(cols)) stop("N too big. Not enough colors in cols.")
if(N > ncol(X)) stop("N too big. Not enough columns in data.")
fit = ClustOfVar::hclustvar(X.quanti = X)
dd.row = as.dendrogram(fit)
ddata_x <- dendro_data(dd.row)
temp = cutree(fit, k = N)
lab <- ggdendro::label(ddata_x)
x = c()
for(i in 1:nrow(lab)){
x[i] = paste("clust", as.vector(temp[lab$label[i] == names(temp)]), sep = "")
}
lab$group <- x
p1 <- ggplot(segment(ddata_x)) +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) +
geom_text(data = lab, aes(label = label, x = x, y = -.05, colour = group), # y = -.05 adds a little space between label and tree
size = 4, hjust = 1) +
scale_x_continuous(expand = c(0, .5)) + # 1. Add half a unit to each end of the vertical axis
expand_limits(y = -0.4) + # 2. Make room for labels
theme_classic() +
scale_colour_manual(values = cols) +
coord_flip() +
theme(legend.position = "none", axis.line = element_blank(),
axis.text = element_blank(), axis.title = element_blank(),
axis.ticks = element_blank(),
axis.ticks.length = unit(0, "cm"))
df2 <- data.frame(cluster = cutree(fit, N),
states = factor(fit$labels, levels = fit$labels[fit$order]))
df3 <- ddply(df2, .(cluster),summarise,pos=mean(as.numeric(states)))
p2 <- ggplot(df2, aes(states, y = 1,
fill = factor(as.character(cluster)))) + # 'as.character' - so that colours match with 10 or more clusters
geom_tile() +
scale_y_continuous(expand = c(0, 0)) +
scale_x_discrete(expand = c(0, 0)) +
coord_flip() +
geom_text(data = df3,aes(x = pos, label = cluster, size = 12)) +
scale_fill_manual(values = cols)
gp1 <- ggplotGrob(p1) # Get ggplot grobs
gp2 <- ggplotGrob(p2)
gp2 <- gp2[6, 4] # 3. Grab plot panel only from tiles plot (thus, no margins)
gp1 <- gtable_add_grob(gp1, gp2, t = 6, l = 2, name = "tiles") # 3. Insert it into dendrogram plot
gp1$widths[2] = unit(1, "cm") # 3. Set width of column containing tiles
grid.newpage()
grid.draw(gp1)
}
plot_color_clust(X, 6)

How can I add a methodological note to a plot ? [duplicate]

I am trying to display some information about the data below the plot created in ggplot2. I would like to plot the N variable using the X axis coordinate of the plot but the Y coordinate needs to be 10% from the bottom of the screen . In fact, the desired Y coordinates are already in the data frame as y_pos variable.
I can think of 3 approaches using ggplot2:
1) Create an empty plot below the actual plot, use the same scale and then use geom_text to plot the data over the blank plot. This approach sort of works but is extremely complicated.
2) Use geom_text to plot the data but somehow use y coordinate as percent of the screen (10%). This would force the numbers to be displayed below the plot. I can't figure out the proper syntax.
3) Use grid.text to display the text. I can easily set it at the 10% from the bottom of the screen but I can't figure how set the X coordindate to match the plot. I tried to use grconvert to capture the initial X position but could not get that to work as well.
Below is the basic plot with the dummy data:
graphics.off() # close graphics windows
library(car)
library(ggplot2) #load ggplot
library(gridExtra) #load Grid
library(RGraphics) # support of the "R graphics" book, on CRAN
#create dummy data
test= data.frame(
Group = c("A", "B", "A","B", "A", "B"),
x = c(1 ,1,2,2,3,3 ),
y = c(33,25,27,36,43,25),
n=c(71,55,65,58,65,58),
y_pos=c(9,6,9,6,9,6)
)
#create ggplot
p1 <- qplot(x, y, data=test, colour=Group) +
ylab("Mean change from baseline") +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1) ) +
opts(
legend.position=c(.1,0.9))
#display plot
p1
The modified gplot below displays numbers of subjects, however they are displayed WITHIN the plot. They force the Y scale to be extended. I would like to display these numbers BELOW the plot.
p1 <- qplot(x, y, data=test, colour=Group) +
ylab("Mean change from baseline") +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1) ) +
opts( plot.margin = unit(c(0,2,2,1), "lines"),
legend.position=c(.1,0.9))+
geom_text(data = test,aes(x=x,y=y_pos,label=n))
p1
A different approach of displaying the numbers involves creating a dummy plot below the actual plot. Here is the code:
graphics.off() # close graphics windows
library(car)
library(ggplot2) #load ggplot
library(gridExtra) #load Grid
library(RGraphics) # support of the "R graphics" book, on CRAN
#create dummy data
test= data.frame(
group = c("A", "B", "A","B", "A", "B"),
x = c(1 ,1,2,2,3,3 ),
y = c(33,25,27,36,43,25),
n=c(71,55,65,58,65,58),
y_pos=c(15,6,15,6,15,6)
)
p1 <- qplot(x, y, data=test, colour=group) +
ylab("Mean change from baseline") +
opts(plot.margin = unit(c(1,2,-1,1), "lines")) +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1) ) +
opts(legend.position="bottom",
legend.title=theme_blank(),
title.text="Line plot using GGPLOT")
p1
p2 <- qplot(x, y, data=test, geom="blank")+
ylab(" ")+
opts( plot.margin = unit(c(0,2,-2,1), "lines"),
axis.line = theme_blank(),
axis.ticks = theme_segment(colour = "white"),
axis.text.x=theme_text(angle=-90,colour="white"),
axis.text.y=theme_text(angle=-90,colour="white"),
panel.background = theme_rect(fill = "transparent",colour = NA),
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank()
)+
geom_text(data = test,aes(x=x,y=y_pos,label=n))
p2
grid.arrange(p1, p2, heights = c(8.5, 1.5), nrow=2 )
However, that is very complicated and would be hard to modify for different data. Ideally, I'd like to be able to pass Y coordinates as percent of the screen.
The current version (>2.1) has a + labs(caption = "text"), which displays an annotation below the plot. This is themeable (font properties,... left/right aligned). See https://github.com/hadley/ggplot2/pull/1582 for examples.
Edited opts has been deprecated, replaced by theme; element_blank has replaced theme_blank; and ggtitle() is used in place of opts(title = ...
Sandy- thank you so much!!!! This does exactly what I want. I do wish we could control the clipping in geom.text or geom.annotate.
I put together the following program if anybody else is interested.
rm(list = ls()) # clear objects
graphics.off() # close graphics windows
library(ggplot2)
library(gridExtra)
#create dummy data
test= data.frame(
group = c("Group 1", "Group 1", "Group 1","Group 2", "Group 2", "Group 2"),
x = c(1 ,2,3,1,2,3 ),
y = c(33,25,27,36,23,25),
n=c(71,55,65,58,65,58),
ypos=c(18,18,18,17,17,17)
)
p1 <- qplot(x=x, y=y, data=test, colour=group) +
ylab("Mean change from baseline") +
theme(plot.margin = unit(c(1,3,8,1), "lines")) +
geom_line()+
scale_x_continuous("Visits", breaks=seq(-1,3) ) +
theme(legend.position="bottom",
legend.title=element_blank())+
ggtitle("Line plot")
# Create the textGrobs
for (ii in 1:nrow(test))
{
#display numbers at each visit
p1=p1+ annotation_custom(grob = textGrob(test$n[ii]),
xmin = test$x[ii],
xmax = test$x[ii],
ymin = test$ypos[ii],
ymax = test$ypos[ii])
#display group text
if (ii %in% c(1,4)) #there is probably a better way
{
p1=p1+ annotation_custom(grob = textGrob(test$group[ii]),
xmin = 0.85,
xmax = 0.85,
ymin = test$ypos[ii],
ymax = test$ypos[ii])
}
}
# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Updated opts() has been replaced with theme()
In the code below, a base plot is drawn, with a wider margin at the bottom of the plot. The textGrob is created, then inserted into the plot using annotation_custom(). Except the text is not visible because it is outside the plot panel - the output is clipped to the panel. But using baptiste's code from here, the clipping can be overrridden. The position is in terms of data units, and both text labels are centred.
library(ggplot2)
library(grid)
# Base plot
df = data.frame(x=seq(1:10), y = seq(1:10))
p = ggplot(data = df, aes(x = x, y = y)) + geom_point() + ylim(0,10) +
theme(plot.margin = unit(c(1,1,3,1), "cm"))
p
# Create the textGrobs
Text1 = textGrob(paste("Largest x-value is", round(max(df$x), 2), sep = " "))
Text2 = textGrob(paste("Mean = ", mean(df$x), sep = ""))
p1 = p + annotation_custom(grob = Text1, xmin = 4, xmax = 4, ymin = -3, ymax = -3) +
annotation_custom(grob = Text2, xmin = 8, xmax = 8, ymin = -3, ymax = -3)
p1
# Code to override clipping
gt <- ggplotGrob(p1)
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or, using grid functions to create and position the label.
p
grid.text((paste("Largest x-value is", max(df$x), sep = " ")),
x = unit(.2, "npc"), y = unit(.1, "npc"), just = c("left", "bottom"),
gp = gpar(fontface = "bold", fontsize = 18, col = "blue"))
Edit
Or, add text grob using gtable functions.
library(ggplot2)
library(grid)
library(gtable)
# Base plot
df = data.frame(x=seq(1:10), y = seq(1:10))
p = ggplot(data = df, aes(x = x, y = y)) + geom_point() + ylim(0,10)
# Construct the text grob
lab = textGrob((paste("Largest x-value is", max(df$x), sep = " ")),
x = unit(.1, "npc"), just = c("left"),
gp = gpar(fontface = "bold", fontsize = 18, col = "blue"))
gp = ggplotGrob(p)
# Add a row below the 2nd from the bottom
gp = gtable_add_rows(gp, unit(2, "grobheight", lab), -2)
# Add 'lab' grob to that row, under the plot panel
gp = gtable_add_grob(gp, lab, t = -2, l = gp$layout[gp$layout$name == "panel",]$l)
grid.newpage()
grid.draw(gp)
Actually the best answer and easiest solution is to use the cowplot package.
Version 0.5.0 of the cowplot package (on CRAN) handles ggplot2 subtitles using the add_sub function.
Use it like so:
diamondsCubed <-ggplot(aes(carat, price), data = diamonds) +
geom_point() +
scale_x_continuous(trans = cuberoot_trans(), limits = c(0.2, 3),
breaks = c(0.2, 0.5, 1, 2, 3)) +
scale_y_continuous(trans = log10_trans(), limits = c(350, 15000),
breaks = c(350, 1000, 5000, 10000, 15000)) +
ggtitle('Price log10 by Cube-Root of Carat') +
theme_xkcd()
ggdraw(add_sub(diamondsCubed, "This is an annotation.\nAnnotations can span multiple lines."))

How to add a ggplot2 subtitle with different size and colour?

I'm using ggplot2 to improve precipitation barplots.
Here's a reproducible example of what I want to achieve:
library(ggplot2)
library(gridExtra)
secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])
m <- ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
opts(axis.text.x=theme_text(angle=-45, hjust=0, vjust=1),
title=expression("Rainfall"), plot.margin = unit(c(1.5, 1, 1, 1), "cm"),
plot.title = theme_text(size = 25, face = "bold", colour = "black", vjust = 5))
z <- arrangeGrob(m, sub = textGrob("Location", x = 0, hjust = -3.5, vjust = -33, gp = gpar(fontsize = 18, col = "gray40"))) #Or guessing x and y with just option
z
I don't know how to avoid using guessing numbers on hjust and vjust on ggplot2? Is there a better way to put a subtitle (not just using \n, but a subtitle with different text color and size)?
I need to be able to use with ggsave to have a pdf file.
Here are two related questions:
Add a footnote citation outside of plot area in R?
How can I add a subtitle and change the font size of ggplot plots in R?
Thanks for any help.
The latest ggplot2 builds (i.e., 2.1.0.9000 or newer) have subtitles and below-plot captions as built-in functionality. That means you can do this:
library(ggplot2) # 2.1.0.9000+
secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])
m <- ggplot(melt.d, aes(x=x, y=y))
m <- m + geom_bar(fill="darkblue", stat="identity")
m <- m + labs(x="Weather stations",
y="Accumulated Rainfall [mm]",
title="Rainfall",
subtitle="Location")
m <- m + theme(axis.text.x=element_text(angle=-45, hjust=0, vjust=1))
m <- m + theme(plot.title=element_text(size=25, hjust=0.5, face="bold", colour="maroon", vjust=-1))
m <- m + theme(plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="black"))
m
Ignore this answer ggplot2 version 2.2.0 has title and subtitle functionality. See #hrbrmstr's answer below.
You could use nested atop functions inside an expression to get different sizes.
EDIT Updated code for ggplot2 0.9.3
m <- ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
ggtitle(expression(atop("Rainfall", atop(italic("Location"), "")))) +
theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1),
#plot.margin = unit(c(1.5, 1, 1, 1), "cm"),
plot.title = element_text(size = 25, face = "bold", colour = "black", vjust = -1))
it's not too hard to add grobs to the gtable and make a fancy title that way,
library(ggplot2)
library(grid)
library(gridExtra)
library(magrittr)
library(gtable)
p <- ggplot() +
theme(plot.margin = unit(c(0.5, 1, 1, 1), "cm"))
lg <- list(textGrob("Rainfall", x=0, hjust=0,
gp = gpar(fontsize=24, fontfamily="Skia", face=2, col="turquoise4")),
textGrob("location", x=0, hjust=0,
gp = gpar(fontsize=14, fontfamily="Zapfino", fontface=3, col="violetred1")),
pointsGrob(pch=21, gp=gpar(col=NA, cex=0.5,fill="steelblue")))
margin <- unit(0.2, "line")
tg <- arrangeGrob(grobs=lg, layout_matrix=matrix(c(1,2,3,3), ncol=2),
widths = unit.c(grobWidth(lg[[1]]), unit(1,"null")),
heights = do.call(unit.c, lapply(lg[c(1,2)], grobHeight)) + margin)
grid.newpage()
ggplotGrob(p) %>%
gtable_add_rows(sum(tg$heights), 0) %>%
gtable_add_grob(grobs=tg, t = 1, l = 4) %>%
grid.draw()
It appears opts is deprecated as of ggplot 2 0.9.1 and no longer functional. This worked for me with the latest versions as of today: + ggtitle(expression(atop("Top line", atop(italic("2nd line"), "")))).
This version uses a gtable function. It allows two lines of text in the title. The text, size, colour, and font face of each line can be set independently of the other. However, the function will modify a plot with a single plot panel only.
Minor edit: Updating to ggplot2 v2.0.0
# The original plot
library(ggplot2)
secu <- seq(1, 16, by = 2)
melt.d <- data.frame(y = secu, x = LETTERS[1:8])
m <- ggplot(melt.d, aes(x = x, y = y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x = "Weather stations", y = "Accumulated Rainfall [mm]") +
theme(axis.text.x = element_text(angle = -45, hjust = 0, vjust = 1))
# The function to set text, size, colour, and face
plot.title = function(plot = NULL, text.1 = NULL, text.2 = NULL,
size.1 = 12, size.2 = 12,
col.1 = "black", col.2 = "black",
face.1 = "plain", face.2 = "plain") {
library(gtable)
library(grid)
gt = ggplotGrob(plot)
text.grob1 = textGrob(text.1, y = unit(.45, "npc"),
gp = gpar(fontsize = size.1, col = col.1, fontface = face.1))
text.grob2 = textGrob(text.2, y = unit(.65, "npc"),
gp = gpar(fontsize = size.2, col = col.2, fontface = face.2))
text = matrix(list(text.grob1, text.grob2), nrow = 2)
text = gtable_matrix(name = "title", grobs = text,
widths = unit(1, "null"),
heights = unit.c(unit(1.1, "grobheight", text.grob1) + unit(0.5, "lines"), unit(1.1, "grobheight", text.grob2) + unit(0.5, "lines")))
gt = gtable_add_grob(gt, text, t = 2, l = 4)
gt$heights[2] = sum(text$heights)
class(gt) = c("Title", class(gt))
gt
}
# A print method for the plot
print.Title <- function(x) {
grid.newpage()
grid.draw(x)
}
# Try it out - modify the original plot
p = plot.title(m, "Rainfall", "Location",
size.1 = 20, size.2 = 15,
col.1 = "red", col.2 = "blue",
face.2 = "italic")
p
You could use wrap the plot in grid.arrange and pass a custom grid-based title,
library(ggplot2)
library(gridExtra)
p <- ggplot() +
theme(plot.margin = unit(c(0.5, 1, 1, 1), "cm"))
tg <- grobTree(textGrob("Rainfall", y=1, vjust=1, gp = gpar(fontsize=25, face=2, col="black")),
textGrob("location", y=0, vjust=0, gp = gpar(fontsize=12, face=3, col="grey50")),
cl="titlegrob")
heightDetails.titlegrob <- function(x) do.call(sum,lapply(x$children, grobHeight))
grid.arrange(p, top = tg)
You might have noticed that Sandy's code doesn't produce a bold title for "Rainfall" - the instruction to make this bold should occur within the atop() function rather than the theme() function.
ggplot(melt.d, aes(x=x, y=y)) +
geom_bar(fill="darkblue", stat = "identity") +
labs(x="Weather stations", y="Accumulated Rainfall [mm]") +
ggtitle(expression(atop(bold("Rainfall"), atop(italic("Location"), "")))) +
theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1),
plot.title = element_text(size = 25, colour = "black", vjust = -1))

Resources