So, I want to add a logo footer to my ggplot, but I want to do so via a function that I can use the + operator with, so I can do: qplot(1:10, 1:10) + add_mylogo()
I can get what I want with this:
library(magick)
library(ggplot2)
mylogo <- image_scale(image_read("https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"), "180")
qplot(1:10, 1:10) + labs(caption="")
grid::grid.raster(mylogo, x = .97, y = .02, just = c('right', 'bottom'), width = unit(1.2, 'inches'))
Which produces:
My problem is that I want to use + to add it to the plot.
So then I tried this:
library(cowplot)
library(magick)
library(ggplot2)
mylogo <- image_scale(image_read("https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"), "380")
qplot(1:3, 1:3)+ labs(caption="") +
draw_image(mylogo, x=3, y = .2, hjust=.7, vjust=0, scale = .5, clip=TRUE)
Which produces:
So now I have it working with a + operator, but I can't figure out how to use any sort of relative positioning. I saw this post about relative positioning using annotate and tried it, but it doesn't work
qplot(1:3, 1:3)+ labs(caption="") +
draw_image(mylogo, x = -Inf, y = Inf, hjust=.7, vjust=0, scale = .5, clip=TRUE)
Error in if (rasterRatio > vpRatio) { :
missing value where TRUE/FALSE needed
So the first option using grid works with relative positioning, but not with the + operator, and the second option using cowplot works with the + operator, but not relative positioning. Is there any way to get both?
You could consider using ggtext:
library(ggplot2)
library(ggtext)
qplot(1:3, 1:3) +
labs(caption = "<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png' width='100'/>") +
theme(plot.caption = element_markdown())
The way you are using draw_image is intended to use the plot coordinates, not relative positioning, as you can see in the draw_image help examples. For using relative positioning you have to change a little bit your code, adding first the image, and then the plot inside a draw_plot call:
ggdraw() +
draw_image(mylogo, scale = 0.2, x = 0.38, y = -0.45) +
draw_plot(
qplot(1:3, 1:3)+ labs(caption="") +
theme(panel.background = element_blank(), plot.background = element_blank())
)
In my tests, positioning seems to be relative to the center of the plot (x = 0, y = 0), so you need negative values to go down in y or left in x.
Another "problem" is that the logo is added before, so you must convert the plot or panel background to transparent or remove them.
Related
I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out with the code below, but as you can see, the labels aren't totally visible.
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + opts(axis.text.x=theme_text(angle=-90))
Change the last line to
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:
The image above is from this blog post.
Use coord_flip()
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
qplot(cut, carat, data = diamonds, geom = "boxplot") +
coord_flip()
Add str_wrap()
# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
coord_flip()
In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:
coord_flip() switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.
ggplot 3.3.0 fixes this by providing guide_axis(angle = 90) (as guide argument to scale_.. or as x argument to guides):
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(angle = 90)) +
# ... or, equivalently:
# guides(x = guide_axis(angle = 90)) +
NULL
From the documentation of the angle argument:
Compared to setting the angle in theme() / element_text(), this also
uses some heuristics to automatically pick the hjust and vjust that
you probably want.
Alternatively, it also provides guide_axis(n.dodge = 2) (as guide argument to scale_.. or as x argument to guides) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
NULL
To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to
q + theme(axis.text.x=element_text(angle=90, hjust=1))
I'd like to provide an alternate solution, a robust solution similar to what I am about to propose was required in the latest version of ggtern, since introducing the canvas rotation feature.
Basically, you need to determine the relative positions using trigonometry, by building a function which returns an element_text object, given angle (ie degrees) and positioning (ie one of x,y,top or right) information.
#Load Required Libraries
library(ggplot2)
library(gridExtra)
#Build Function to Return Element Text Object
rotatedAxisElementText = function(angle,position='x'){
angle = angle[1];
position = position[1]
positions = list(x=0,y=90,top=180,right=270)
if(!position %in% names(positions))
stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
if(!is.numeric(angle))
stop("'angle' must be numeric",call.=FALSE)
rads = (angle - positions[[ position ]])*pi/180
hjust = 0.5*(1 - sin(rads))
vjust = 0.5*(1 + cos(rads))
element_text(angle=angle,vjust=vjust,hjust=hjust)
}
Frankly, in my opinion, I think that an 'auto' option should be made available in ggplot2 for the hjust and vjust arguments, when specifying the angle, anyway, lets demonstrate how the above works.
#Demonstrate Usage for a Variety of Rotations
df = data.frame(x=0.5,y=0.5)
plots = lapply(seq(0,90,length.out=4),function(a){
ggplot(df,aes(x,y)) +
geom_point() +
theme(axis.text.x = rotatedAxisElementText(a,'x'),
axis.text.y = rotatedAxisElementText(a,'y')) +
labs(title = sprintf("Rotated %s",a))
})
grid.arrange(grobs=plots)
Which produces the following:
The ggpubr package offers a shortcut that does the right thing by default (right align text, middle align text box to tick):
library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()
Created on 2018-11-06 by the reprex package (v0.2.1)
Found with a GitHub search for the relevant argument names: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code
OUTDATED - see this answer for a simpler approach
To obtain readable x tick labels without additional dependencies, you want to use:
... +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
...
This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1) and their centers horizontally with the corresponding tick mark (vjust = 0.5).
Full example:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
Note, that vertical/horizontal justification parameters vjust/hjust of element_text are relative to the text. Therefore, vjust is responsible for the horizontal alignment.
Without vjust = 0.5 it would look like this:
q + theme(axis.text.x = element_text(angle = 90, hjust = 1))
Without hjust = 1 it would look like this:
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1)).
All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.
An alternative to coord_flip() is to use the ggstance package.
The advantage is that it makes it easier to combine the graphs with other graph types and you can, maybe more importantly, set fixed scale ratios for your coordinate system.
library(ggplot2)
library(ggstance)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(data=diamonds, aes(carat, cut)) + geom_boxploth()
Created on 2020-03-11 by the reprex package (v0.3.0)
Also with ggplot2 3.3+, we can make horizontal plots without coord_flip() as it supports bi-directional geoms, simply swapping x and y axis. https://cmdlinetips.com/2020/03/ggplot2-2-3-0-is-here-two-new-features-you-must-know/
I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out with the code below, but as you can see, the labels aren't totally visible.
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + opts(axis.text.x=theme_text(angle=-90))
Change the last line to
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:
The image above is from this blog post.
Use coord_flip()
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
qplot(cut, carat, data = diamonds, geom = "boxplot") +
coord_flip()
Add str_wrap()
# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
coord_flip()
In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:
coord_flip() switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.
ggplot 3.3.0 fixes this by providing guide_axis(angle = 90) (as guide argument to scale_.. or as x argument to guides):
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(angle = 90)) +
# ... or, equivalently:
# guides(x = guide_axis(angle = 90)) +
NULL
From the documentation of the angle argument:
Compared to setting the angle in theme() / element_text(), this also
uses some heuristics to automatically pick the hjust and vjust that
you probably want.
Alternatively, it also provides guide_axis(n.dodge = 2) (as guide argument to scale_.. or as x argument to guides) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
NULL
To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to
q + theme(axis.text.x=element_text(angle=90, hjust=1))
I'd like to provide an alternate solution, a robust solution similar to what I am about to propose was required in the latest version of ggtern, since introducing the canvas rotation feature.
Basically, you need to determine the relative positions using trigonometry, by building a function which returns an element_text object, given angle (ie degrees) and positioning (ie one of x,y,top or right) information.
#Load Required Libraries
library(ggplot2)
library(gridExtra)
#Build Function to Return Element Text Object
rotatedAxisElementText = function(angle,position='x'){
angle = angle[1];
position = position[1]
positions = list(x=0,y=90,top=180,right=270)
if(!position %in% names(positions))
stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
if(!is.numeric(angle))
stop("'angle' must be numeric",call.=FALSE)
rads = (angle - positions[[ position ]])*pi/180
hjust = 0.5*(1 - sin(rads))
vjust = 0.5*(1 + cos(rads))
element_text(angle=angle,vjust=vjust,hjust=hjust)
}
Frankly, in my opinion, I think that an 'auto' option should be made available in ggplot2 for the hjust and vjust arguments, when specifying the angle, anyway, lets demonstrate how the above works.
#Demonstrate Usage for a Variety of Rotations
df = data.frame(x=0.5,y=0.5)
plots = lapply(seq(0,90,length.out=4),function(a){
ggplot(df,aes(x,y)) +
geom_point() +
theme(axis.text.x = rotatedAxisElementText(a,'x'),
axis.text.y = rotatedAxisElementText(a,'y')) +
labs(title = sprintf("Rotated %s",a))
})
grid.arrange(grobs=plots)
Which produces the following:
The ggpubr package offers a shortcut that does the right thing by default (right align text, middle align text box to tick):
library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()
Created on 2018-11-06 by the reprex package (v0.2.1)
Found with a GitHub search for the relevant argument names: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code
OUTDATED - see this answer for a simpler approach
To obtain readable x tick labels without additional dependencies, you want to use:
... +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
...
This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1) and their centers horizontally with the corresponding tick mark (vjust = 0.5).
Full example:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
Note, that vertical/horizontal justification parameters vjust/hjust of element_text are relative to the text. Therefore, vjust is responsible for the horizontal alignment.
Without vjust = 0.5 it would look like this:
q + theme(axis.text.x = element_text(angle = 90, hjust = 1))
Without hjust = 1 it would look like this:
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1)).
All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.
An alternative to coord_flip() is to use the ggstance package.
The advantage is that it makes it easier to combine the graphs with other graph types and you can, maybe more importantly, set fixed scale ratios for your coordinate system.
library(ggplot2)
library(ggstance)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(data=diamonds, aes(carat, cut)) + geom_boxploth()
Created on 2020-03-11 by the reprex package (v0.3.0)
Also with ggplot2 3.3+, we can make horizontal plots without coord_flip() as it supports bi-directional geoms, simply swapping x and y axis. https://cmdlinetips.com/2020/03/ggplot2-2-3-0-is-here-two-new-features-you-must-know/
I'm trying to find a way to insert an image into the corner of a ggplot panel, without specifying the coordinates manually each time.
In this instance, I'm attempting to place a graphic in the top right.
library(magick)
library(ggplot2)
library(datasets)
homer <- magick::image_read("http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png")
g <- ggplot(mpg, aes(class)) +
geom_bar() +
labs(
title = "Count of Auto by Class",
subtitle = "Text to Create More Space")
g + annotation_custom(rasterGrob(homer, interpolate = TRUE),
xmax = Inf, ymax = Inf) +
coord_cartesian(clip = "off")
I have found some examples that come close to solving this:
Inserting an image to ggplot outside the chart area
Corner Labels in ggplot2
But neither quite get there. Specifying the exact location at which to place the image seems to require quite a bit of trial-and-error on each plot created, especially when x is categorical.
I would also like to maintain the size of my original image; the code I've used above seems to stretch it across the plot.
Thanks in advance...much appreciated.
try this
library(grid)
a <- rasterGrob(homer, interpolate = TRUE,
width=unit(1,'cm'),
x = unit(1,"npc"), y = unit(1,"npc"),
hjust = 1, vjust=1)
g + annotation_custom(grob = a)
I am trying to recreate a figure from a GGplot2 seminar http://dl.dropbox.com/u/42707925/ggplot2/ggplot2slides.pdf.
In this case, I am trying to generate Example 5, with jittered data points subject to a dodge. When I run the code, the points are centered around the correct line, but have no jitter.
Here is the code directly from the presentation.
set.seed(12345)
hillest<-c(rep(1.1,100*4*3)+rnorm(100*4*3,sd=0.2),
rep(1.9,100*4*3)+rnorm(100*4*3,sd=0.2))
rep<-rep(1:100,4*3*2)
process<-rep(rep(c("Process 1","Process 2","Process 3","Process 4"),each=100),3*2)
memorypar<-rep(rep(c("0.1","0.2","0.3"),each=4*100),2)
tailindex<-rep(c("1.1","1.9"),each=3*4*100)
ex5<-data.frame(hillest=hillest,rep=rep,process=process,memorypar=memorypar, tailindex=tailindex)
stat_sum_df <- function(fun, geom="crossbar", ...) {stat_summary(fun.data=fun, geom=geom, ...) }
dodge <- position_dodge(width=0.9)
p<- ggplot(ex5,aes(x=tailindex ,y=hillest,color=memorypar))
p<- p + facet_wrap(~process,nrow=2) + geom_jitter(position=dodge) +geom_boxplot(position=dodge)
p
In ggplot2 version 1.0.0 there is new position named position_jitterdodge() that is made for such situation. This postion should be used inside the geom_point() and there should be fill= used inside the aes() to show by which variable to dodge your data. To control the width of dodging argument dodge.width= should be used.
ggplot(ex5, aes(x=tailindex, y=hillest, color=memorypar, fill=memorypar)) +
facet_wrap(~process, nrow=2) +
geom_point(position=position_jitterdodge(dodge.width=0.9)) +
geom_boxplot(fill="white", outlier.colour=NA, position=position_dodge(width=0.9))
EDIT: There is a better solution with ggplot2 version 1.0.0 using position_jitterdodge. See #Didzis Elferts' answer. Note that dodge.width controls the width of the dodging and jitter.width controls the width of the jittering.
I'm not sure how the code produced the graph in the pdf.
But does something like this get you close to what you're after?
I convert tailindex and memorypar to numeric; add them together; and the result is the x coordinate for the geom_jitter layer. There's probably a more effective way to do it. Also, I'd like to see how dodging geom_boxplot and geom_jitter, and with no jittering, will produce the graph in the pdf.
library(ggplot2)
dodge <- position_dodge(width = 0.9)
ex5$memorypar2 <- as.numeric(ex5$tailindex) +
3 * (as.numeric(as.character(ex5$memorypar)) - 0.2)
p <- ggplot(ex5,aes(x=tailindex , y=hillest)) +
scale_x_discrete() +
geom_jitter(aes(colour = memorypar, x = memorypar2),
position = position_jitter(width = .05), alpha = 0.5) +
geom_boxplot(aes(colour = memorypar), outlier.colour = NA, position = dodge) +
facet_wrap(~ process, nrow = 2)
p
In my plot I have both legends and text annotations. For legends, I can specify
legend.justification=c(1,0), legend.position=c(1,0)
to locate the position relative to the plotting region (e.g. topright, bottomleft). However, when I put an annotate layer (http://docs.ggplot2.org/0.9.3.1/annotate.html), it seems that I can only specify the coordinates of the text
annotate("text", x = 8e-7, y = 1e-5, label=data.note, size = 5)
instead of the position of the plotting region (I want to put the text in the bottomleft corner). The length of the text (label) may vary for different plots. Is there a way to achieve this? Thanks!
You can use the fact that -Inf and Inf will get mapped to the extremes of the position scales without extending them to place it in the bottom left corner. hjust and vjust are needed to make the reference point the lower left corner of your text. [using jlhoward's mock data.]
set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df, aes(x,y)) +geom_point()+
annotate("text",x=-Inf,y=-Inf,hjust=0,vjust=0,label="Text annotation")
Is this what you're looking for??
set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df, aes(x,y)) +geom_point()+
annotate("text",x=min(df$x),y=min(df$y),hjust=.2,label="Text annotation")
There will probably be a bit of experimentation with hjust=... needed to get this exactly at the bottom left.
The "Inf" solution has problems when you want multi-line text. In addition, it there is no margin between the text and the panel edge, which is ugly. The other solution requires explicit mention of the data which is not good either.
The desired effect can be achieved nicely with annotation_custom (or in my example, the proto Geom directly). You have configurable margin, text and box justification.
The added bonus in the following code is that you can specify which facet to annotate with something like facets=data.frame(cat1='blue', cat2='tall').
library("ggplot2")
annotate_textp <- function(label, x, y, facets=NULL, hjust=0, vjust=0, color='black', alpha=NA,
family=thm$text$family, size=thm$text$size, fontface=1, lineheight=1.0,
box_just=ifelse(c(x,y)<0.5,0,1), margin=unit(size/2, 'pt'), thm=theme_get()) {
x <- scales::squish_infinite(x)
y <- scales::squish_infinite(y)
data <- if (is.null(facets)) data.frame(x=NA) else data.frame(x=NA, facets)
tg <- grid::textGrob(
label, x=0, y=0, hjust=hjust, vjust=vjust,
gp=grid::gpar(col=alpha(color, alpha), fontsize=size, fontfamily=family, fontface=fontface, lineheight=lineheight)
)
ts <- grid::unit.c(grid::grobWidth(tg), grid::grobHeight(tg))
vp <- grid::viewport(x=x, y=y, width=ts[1], height=ts[2], just=box_just)
tg <- grid::editGrob(tg, x=ts[1]*hjust, y=ts[2]*vjust, vp=vp)
inner <- grid::grobTree(tg, vp=grid::viewport(width=unit(1, 'npc')-margin*2, height=unit(1, 'npc')-margin*2))
layer(
data = NULL,
stat = StatIdentity,
position = PositionIdentity,
geom = GeomCustomAnn,
inherit.aes = TRUE,
params = list(
grob=grid::grobTree(inner),
xmin=-Inf,
xmax=Inf,
ymin=-Inf,
ymax=Inf
)
)
}
qplot(1:10,1:10) + annotate_text2('some long text\nx = 1', x=0.5, y=0.5, hjust=1)