Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have annotated text style to inherit from theme_set() options

Tags:

r

ggplot2

How to uniformly define text style (size and family) for both plot text elements and additional annotations?

The following MWE

library(ggplot2) 

data1.df <- data.frame(Plant = c("Plant1", "Plant1", "Plant1", "Plant2", "Plant2", 
                                 "Plant2"), Type = c(1, 2, 3, 1, 2, 3), Axis1 = c(0.2, -0.4, 0.8, -0.2, -0.7, 
                                                                                  0.1), Axis2 = c(0.5, 0.3, -0.1, -0.3, -0.1, -0.8))

theme_set(theme_bw() + theme(text=element_text(family="Palatino", size=10)))

ggplot(data1.df, aes(x = Axis1, y = Axis2, shape = Plant, color = Type)) + geom_point(size = 5) +  annotate("text", x=0.4, y=0.0, label="Label", fontface="italic") + theme(legend.position="none")

produces

enter image description here

with "Label" not consistent with the theme element_text() definitions.

like image 672
CptNemo Avatar asked Nov 19 '13 22:11

CptNemo


1 Answers

If ggplot2 is loaded then this should give you the properties currently in force (if they are different than the defaults):

theme(text = element_text())$text[ c("family", "size") ]

?annotate tells us that ... "Unlike typical a geom function, the properties of the geoms are not mapped from variables of a data frame, but are instead in as vectors.". I'm assuming this to mean that annotate does not look in theme() for its font information, although that is not specifically covered by that sentence. There is also a later comment that makes me think this might be by design: " ... but all other aesthetics are set. This means that layers created with this function will never affect the legend."

And the comment in ?annotate: "These are not scaled, so you can do (e.g.) colour = "red" to get a red point." I think the defaults for axis have a particular ratio on sizes but have not manage to find the specifics in the help files. This seems to give similar size for the annotation as for the axis titles:

ggplot(data1.df, aes(x = Axis1, y = Axis2, shape = Plant, color = Type)) + 
       geom_point(size = 5) +  
       annotate("text", x=0.4, y=0.0, label="Label", 
                 family= theme_get()$text[["family"]], 
                 size= theme_get()$text[["size"]]/2.5, 
                 fontface="italic") + 
       theme(legend.position="none")

If you are interested in pursuing the "why" use 2.5 question you can look at ?rel and the example that uses theme(axis.title.x = element_text(size = rel(2.5))).

like image 122
IRTFM Avatar answered Oct 22 '22 08:10

IRTFM