Manipulating axis titles in ggpairs (GGally) - r

I'm using the code below to generate the following chart.
# Setup
data(airquality)
# Device start
png(filename = "example.png", units = "cm", width = 20, height = 14, res = 300)
# Define chart
pairs.chrt <- ggpairs(airquality,
lower = list(continuous = "smooth"),
diag = list(continuous = "blank"),
upper = list(continuous = "blank")) +
theme(legend.position = "none",
panel.grid.major = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_text(angle = 180, vjust = 1, color = "black"),
panel.border = element_rect(fill = NA))
# Device off and print
print(pairs.chrt)
dev.off()
I'm currently trying to modify the display of the axis titles. In particular, I would like for the axis titles to be:
Placed at a further distance from axis labels
Placed at an angle
As an example, I would like to obtain axis titles similar to the ones pictured below (I'm interested in axis labels only, not in rest of the chart):
Taken from : Geovisualist
I' tried adjusting my syntax changing the axis.title.x to different values but it does not yield the desired results. For instance running the code with angle = 45.
axis.title.x = element_text(angle = 45, vjust = 1, color = "black"),
panel.border = element_rect(fill = NA))
returns the same chart. I was able to control the axis labels by changing the axis.text.x for instance but I can't find the answer how to control the axis titles in this plot. Any help will be much appreciated.

Short answer: There doesn't seem to be an elegant or easy way to do it, but here's a workaround.
I dug into the ggpairs source code (in the GGally package source available from CRAN) to see how the variable labels are actually drawn. The relevant function in ggpairs.R is print.ggpairs. It turns out the variable labels aren't part of the ggplot objects in each cell of the plot matrix -- i.e. they're not axis titles, which is why they aren't affected by using theme(axis.title.x = element_text(angle = 45) or similar.
Rather, they seem to be drawn as text annotations using grid.text (in package 'grid'). grid.text takes arguments including x, y, hjust, vjust, rot (where rot is angle of rotation), as well as font size, font family, etc. using gpar (see ?grid.text), but it looks like there is currently no way to pass in different values of those parameters to print.ggpairs -- they're fixed at default values.
You can work around it by leaving your variable labels blank to begin with, and then adding them on later with customized placement, rotation, and styling, using a modification of the relevant part of the print.ggpairs code. I came up with the following modification. (Incidentally, because the original GGally source code was released under a GPL-3 license, so is this modification.)
customize.labels <- function(
plotObj,
varLabels = NULL, #vector of variable labels
titleLabel = NULL, #string for title
leftWidthProportion = 0.2, #if you changed these from default...
bottomHeightProportion = 0.1, #when calling print(plotObj),...
spacingProportion = 0.03, #then change them the same way here so labels will line up with plot matrix.
left.opts = NULL, #see pattern in left.opts.default
bottom.opts = NULL, #see pattern in bottom.opts.default
title.opts = NULL) { #see pattern in title.opts.default
require('grid')
vplayout <- function(x, y) {
viewport(layout.pos.row = x, layout.pos.col = y)
}
numCol <- length(plotObj$columns)
if (is.null(varLabels)) {
varLabels <- colnames(plotObj$data)
#default to using the column names of the data
} else if (length(varLabels) != numCol){
stop('Length of varLabels must be equal to the number of columns')
}
#set defaults for left margin label style
left.opts.default <- list(x=0,
y=0.5,
rot=90,
just=c('centre', 'centre'), #first gives horizontal justification, second gives vertical
gp=list(fontsize=get.gpar('fontsize')))
#set defaults for bottom margin label style
bottom.opts.default <- list(x=0,
y=0.5,
rot=0,
just=c('centre', 'centre'),#first gives horizontal justification, second gives vertical
gp=list(fontsize=get.gpar('fontsize')))
#set defaults for title text style
title.opts.default <- list(x = 0.5,
y = 1,
just = c(.5,1),
gp=list(fontsize=15))
#if opts not provided, go with defaults
if (is.null(left.opts)) {
left.opts <- left.opts.default
} else{
not.given <- names(left.opts.default)[!names(left.opts.default) %in%
names(left.opts)]
if (length(not.given)>0){
left.opts[not.given] <- left.opts.default[not.given]
}
}
if (is.null(bottom.opts)) {
bottom.opts <- bottom.opts.default
} else{
not.given <- names(bottom.opts.default)[!names(bottom.opts.default) %in%
names(bottom.opts)]
if (length(not.given)>0){
bottom.opts[not.given] <- bottom.opts.default[not.given]
}
}
if (is.null(title.opts)) {
title.opts <- title.opts.default
} else{
not.given <- names(title.opts.default)[!names(title.opts.default) %in%
names(title.opts)]
if (length(not.given)>0){
title.opts[not.given] <- title.opts.default[not.given]
}
}
showLabels <- TRUE
viewPortWidths <- c(leftWidthProportion,
1,
rep(c(spacingProportion,1),
numCol - 1))
viewPortHeights <- c(rep(c(1,
spacingProportion),
numCol - 1),
1,
bottomHeightProportion)
viewPortCount <- length(viewPortWidths)
if(!is.null(titleLabel)){
pushViewport(viewport(height = unit(1,"npc") - unit(.4,"lines")))
do.call('grid.text', c(title.opts[names(title.opts)!='gp'],
list(label=titleLabel,
gp=do.call('gpar',
title.opts[['gp']]))))
popViewport()
}
# viewport for Left Names
pushViewport(viewport(width=unit(1, "npc") - unit(2,"lines"),
height=unit(1, "npc") - unit(3, "lines")))
## new for axis spacingProportion
pushViewport(viewport(layout = grid.layout(
viewPortCount, viewPortCount,
widths = viewPortWidths, heights = viewPortHeights
)))
# Left Side
for(i in 1:numCol){
do.call('grid.text',
c(left.opts[names(left.opts)!='gp'],
list(label=varLabels[i],
vp = vplayout(as.numeric(i) * 2 - 1 ,1),
gp=do.call('gpar',
left.opts[['gp']]))))
}
popViewport()# layout
popViewport()# spacing
# viewport for Bottom Names
pushViewport(viewport(width=unit(1, "npc") - unit(3,"lines"),
height=unit(1, "npc") - unit(2, "lines")))
## new for axis spacing
pushViewport(viewport(layout = grid.layout(
viewPortCount, viewPortCount,
widths = viewPortWidths, heights = viewPortHeights)))
# Bottom Side
for(i in 1:numCol){
do.call('grid.text',
c(bottom.opts[names(bottom.opts)!='gp'],
list(label=varLabels[i],
vp = vplayout(2*numCol, 2*i),
gp=do.call('gpar',
bottom.opts[['gp']]))))
}
popViewport() #layout
popViewport() #spacing
}
And here's an example of calling that function:
require('data.table')
require('GGally')
require('grid')
fake.data <- data.table(test.1=rnorm(50), #make some fake data for demonstration
test.2=rnorm(50),
test.3=rnorm(50),
test.4=rnorm(50))
g <- ggpairs(data=fake.data,
columnLabels=rep('', ncol(fake.data)))
#Set columnLabels to a vector of blank column labels
#so that original variable labels will be blank.
print(g)
customize.labels(plotObj=g,
titleLabel = 'Test plot', #string for title
left.opts = list(x=-0.5, #moves farther to the left, away from vertical axis
y=0.5, #centered with respect to vertical axis
just=c('center', 'center'),
rot=90,
gp=list(col='red',
fontface='italic',
fontsize=12)),
bottom.opts = list(x=0.5,
y=0,
rot=45, #angle the text at 45 degrees
just=c('center', 'top'),
gp=list(col='red',
fontface='bold',
fontsize=10)),
title.opts = list(gp=list(col='green',
fontface='bold.italic'))
)
(This makes some very ugly labels -- for the purposes of demonstration only!)
I didn't tinker with placing the labels somewhere other than the left and bottom -- as in your Geovisualist example -- but I think you'd do it by changing the arguments to vplayout in the "Left Side" and "Bottom Side" pieces of code in customize.labels. The x and y coordinates in grid.text are defined relative to a viewport, which divides the display area into a grid in
pushViewport(viewport(layout = grid.layout(
viewPortCount, viewPortCount,
widths = viewPortWidths, heights = viewPortHeights
)))
The call to vplayout specifies which cell of the grid is being used to position each label.

Caveat: not a complete answer but perhaps suggests a way to approach it. You can do this by editing the grid objects.
# Plot in current window
# use left to add space at y axis and bottom for below xaxis
# see ?print.ggpairs
print(pairs.chrt, left = 1, bottom = 1)
# Get list of grobs in current window and extract the axis labels
# note if you add a title this will add another text grob,
# so you will need to tweak this so not to extract it
g <- grid.ls(print=FALSE)
idx <- g$name[grep("text", g$name)]
# Rotate yaxis labels
# change the rot value to the angle you want
for(i in idx[1:6]) {
grid.edit(gPath(i), rot=0, hjust=0.25, gp = gpar(col="red"))
}
# Remove extra ones if you want
n <- ncol(airquality)
lapply(idx[c(1, 2*n)], grid.remove)

My answer won't fix the diagonal label issue but it will fix the overlay one.
I had this issue with the report I am currently writing, where the axis titles were always over the axes, especially in ggpairs. I used a combination of adjusting the out.height/out.width in conjunction with fig.height/fig.width. Separately the problem was not fixed, but together it was. fig.height/fig.width took the labels away from the axis but made them too small to read, and out.height/out.width just made the plot bigger with the problem unchanged. The below gave me the results shown:
out.height="400px", out.width="400px",fig.height=10,fig.width=10
before:plot with issues
after:

Related

Lock aspect ratio on part of grid

I'm trying to write a function wherein our company logo is automatically added to each graph on export as part of a function, next to the title and subtitle. The dimensions of each output will depend on the needs at the time, so having a set size won't be particularly helpful unfortunately.
To do this, I've generated a series of grids to slot everything together, as per the below (using the iris dataset).
library(datasets)
library(tidyverse)
library(gridExtra)
library(grid)
library(png)
m <- readPNG("Rlogo.png") # download from: https://www.r-project.org/logo/Rlogo.png
plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_col() +
ggtitle("Title goes here",
subtitle = "subtitle down here")
txtTitle <- plot$labels$title
txtSubTitle <- plot$labels$subtitle
plot$labels$title <- NULL
plot$labels$subtitle <- NULL
buffer <- grobTree(rectGrob(gp = gpar(fill = "white", col = "white")))
Title <- grobTree(textGrob(label = txtTitle,
hjust = 1,
x = 0.98))
SubTitle <- textGrob(label = txtSubTitle,
hjust = 1,
x = 0.98)
Logo <- grobTree(rasterGrob(m, x = 0.02, hjust = 0))
TitlesGrid <- grid.arrange(Title, SubTitle, ncol = 1)
TopGrid <- grid.arrange(Logo, TitlesGrid, widths = c(1, 7), ncol = 2)
AllGrid <- grid.arrange(TopGrid, arrangeGrob(plot), heights = c(1,7))
This provides the following outputs at different aspect ratios.
The first example has a nice gap between the title and subtitle whereas there is too much for the second one. How would I make it so that the height of TopGrid is fixed to an absolute size, but the rest fills to the size desired?
Grid graphics has the concept of absolute and relative units. Absolute units (such as "cm", "in", "pt") always stay the same size, regardless of the viewport size. Relative units (called "null") expand or shrink as needed. In a regular ggplot2 object, the plot panel is specified in relative units while the various elements around the panel, such as title, axis ticks, etc. are specified in absolute units.
You specify absolute or relative units with the unit() function:
> library(grid)
> unit(1, "cm")
[1] 1cm
> unit(1, "null")
[1] 1null
In your case, the heights argument of grid.arrange can take arbitrary grid unit objects, so you just have to give the top height an absolute unit:
grid.arrange(TopGrid, arrangeGrob(plot), heights = unit(c(1, 1), c("cm", "null")))

grid.arrange: manipulating labels, legends, spacing in parallel coordinate plots

I wrote a function that will plot a user-specified number of parallel coordinate subplots, all in one big plot with one column:
library(gridExtra)
library(GGally)
plotClusterPar = function(cNum){
plot_i = vector("list", length=cNum)
for (i in 1:cNum){
x = data.frame(a=runif(100,0,1),b=runif(100,0,1),c=runif(100,0,1),d=runif(100,0,1))
plot_i[[i]] = ggparcoord(x, columns=1:4, scale="globalminmax", alphaLines = 0.9)+ylab("Count")
}
p = do.call("grid.arrange", c(plot_i, ncol=1))
}
The user will call (to create 3 subplots):
plotClusterPar(3)
There are four things I am trying to do, and when I try them, I get errors, so I left it at its bare working syntax! Here is what I aim to do:
1) I desire to have one y-axis label "Count", rather than an individual one for each subplot.
2) I do not wish to have any x-axis label. As default (currently), there is the label "variable" indicated under each subplot. If extra space (in between subplots) is created after removing an x-axis label, then I would like to erase that newly-created horizontal space (in between subplots).
3) I hope to color all lines in each subplot the same color. For instance, the top subplot would have all red lines, the next subplot would have all blue lines, etc. I do not mind what the colors are!
4) I strive to have a color legend at the bottom of all the subplots. (Similar to the first answer here: Universal x axis label and legend at bottom using grid.arrange), but of course the number of colors is just equal to the number of subplots.
EDIT:
I have tried to change the color, using things like:
plot_i[[i]] = ggparcoord(x, columns=1:4, scale="globalminmax", alphaLines = 0.9, colour=i)+ylab("Count")
Or hardcoding, which would not even work, because I have a loop. But this still does not work:
plot_i[[i]] = ggparcoord(x, columns=1:4, scale="globalminmax", alphaLines = 0.9, colour="red")+ylab("Count")
I tried adding colour as a layer, but that does not work:
plot_i[[i]] = ggparcoord(x, columns=1:4, scale="globalminmax", alphaLines = 0.9)+ylab("Count")+colour("red")
I also tried to give a common plot title and y-axis:
plotClusterPar = function(cNum){
plot_i = vector("list", length=cNum)
for (i in 1:cNum){
x = data.frame(a=runif(100,0,1),b=runif(100,0,1),c=runif(100,0,1),d=runif(100,0,1))
plot_i[[i]] = ggparcoord(x, columns=1:4, scale="globalminmax", alphaLines = 0.9)
}
p = do.call("grid.arrange", c(plot_i, ncol=1, main = textGrob("Main Title", vjust = 1, gp = gpar(fontface = "bold", cex = 1.5)), left = textGrob("Global Y-axis Label", rot = 90, vjust = 1)))
}
But this led to an error:
Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main, :
input must be grobs!

add second axis label to facetted plot

How does one add a second axis label to facetted plots?
I realize in most cases they should be the same, but I have a top row with skill metrics for different models while the bottom row is the difference in skill so I'd like to include bquote(Delta*.(costlong)) below the existing axis label, and to the left of the 2nd row of facets.
I've tried
`labs(y=bquote(Delta*.(costlong)*" "*.(costlong)*" "))+`
but its impossible to center well and it moves when exporting.
I've also played with
+annotation_custom(textGrob('bquote(Delta*.(costlong))),xmin=-20,xmax=-10,ymin=0,ymax=.2)
but it doesn't show up. I am limiting my x axis from 0 to 160.
here is some data and plotting code:
costlong=bquote(r^2)
skill.m=data.frame(doy=seq(1,160),yr=2000:2001,variable=factor(c('skill_phvfull','skill_phvrcnfull','fulldiff'),levels=c('skill_phvfull','skill_phvrcnfull','fulldiff')),value=runif(2*3*160,0,.6))
skill.m$set=ifelse(grepl('skill',as.character(skill.m$variable)),'data','diff')
skill.m$set=as.factor(skill.m$set)
skill.m[grepl('diff',as.character(skill.m$variable)),'value']=skill.m[grepl('diff',as.character(skill.m$variable)),'value']/3
ggplot(skill.m)+
geom_point(aes(x=as.numeric(doy),y=value,colour=variable),alpha=.75,size=1)+
facet_grid(set~yr,scale='free',space='free')+
labs(y=costlong)+
scale_colour_brewer(name='',palette='Set1',labels=c('PHV (blended)','PHV+RCN (blended)','Blended Skill Difference'))+
scale_x_continuous('day of year',limits=c(1,160),labels=c(1,seq(30,160,30)),breaks=c(1,seq(30,160,30)))+
scale_y_continuous(breaks=seq(0,.7,.1),labels=seq(0,.7,.1))+
guides(colour=guide_legend(override.aes=list(alpha=1,size=2)))+
theme_bw()+
theme(axis.line=element_line(colour='grey10'),
strip.background=element_rect(fill='white',colour='white'),
strip.text=element_text(face='bold',size='12'),
axis.text.x=element_text(size=8,angle=90,hjust=1,vjust=.5),
axis.text.y=element_text(size=8,angle=0),
legend.key=element_rect(colour='white'),
legend.position = "bottom",
legend.box = "horizontal")
any suggestions?
One way is to use gtable functions. Draw the ggplot with a blank y label. Then convert the ggplot to a grob, construct two text grobs for the two labels (the upper component and the lower component), then insert the text grobs into the layout.
library(ggplot2)
library(gtable)
library(grid)
costlong=bquote(r^2)
skill.m=data.frame(doy=seq(1,160),yr=2000:2001,variable=factor(c('skill_phvfull','skill_phvrcnfull','fulldiff'),levels=c('skill_phvfull','skill_phvrcnfull','fulldiff')),value=runif(2*3*160,0,.6))
skill.m$set=ifelse(grepl('skill',as.character(skill.m$variable)),'data','diff')
skill.m$set=as.factor(skill.m$set)
skill.m[grepl('diff',as.character(skill.m$variable)),'value']=skill.m[grepl('diff',as.character(skill.m$variable)),'value']/3
p = ggplot(skill.m)+
geom_point(aes(x=as.numeric(doy),y=value,colour=variable),alpha=.75,size=1)+
facet_grid(set~yr,scale='free',space='free')+
labs(y="")+
scale_colour_brewer(name='',palette='Set1',labels=c('PHV (blended)','PHV+RCN (blended)','Blended Skill Difference'))+
scale_x_continuous('day of year',limits=c(1,160),labels=c(1,seq(30,160,30)),breaks=c(1,seq(30,160,30)))+
scale_y_continuous(breaks=seq(0,.7,.1),labels=seq(0,.7,.1))+
guides(colour=guide_legend(override.aes=list(alpha=1,size=2)))+
theme_bw()+
theme(axis.line=element_line(colour='grey10'),
strip.background=element_rect(fill=NA,colour=NA),
strip.text=element_text(face='bold',size='12'),
axis.text.x=element_text(size=8,angle=90,hjust=1,vjust=.5),
axis.text.y=element_text(size=8,angle=0),
legend.key=element_rect(colour='white'),
legend.position = "bottom",
legend.box = "horizontal")
# Convert the plot to a grob
gt = ggplotGrob(p)
# Check the layout
gtable_show_layout(gt) # To manually find the row and column for the labels
# Construct text grobs - one for each label
labL = textGrob(expression(bold(Delta * r^2)), rot = 90,
gp = gpar(fontsize = 12))
labU = textGrob(expression(bold(r^2)), rot = 90,
gp = gpar(fontsize = 12))
# Insert the text grobs into the layout
gt <- gtable_add_grob(gt, labL, t = 9, l = 2)
gt <- gtable_add_grob(gt, labU, t = 7, l = 2)
# Make the column a little wider
gt$widths[2] = unit(2, "lines")
# Draw it
grid.newpage()
grid.draw(gt)

How to manipulate y-axis text labels in R varImpPlot?

The following sample resembles my dataset:
require(randomForest)
alpha = c(1,2,3,4,5,6)
bravo = c(2,3,4,5,6,7)
charlie = c(2,6,5,3,5,6)
mydata = data.frame(alpha,bravo,charlie)
myrf = randomForest(alpha~bravo+charlie, data = mydata, importance = TRUE)
varImpPlot(myrf, type = 2)
I cannot seem to control the placement of the y-axis labels in varImpPlot. I have tried altering the plot parameters (e.g. mar, oma), with no success. I need the y-axis labels shifted to the left in order to produce a PDF with proper label placement.
How can I shift the y-axis labels to the left?
I tried to use adj parameter but it produces a bug. As varImpPlot , use dotchart behind, Here a version using lattice dotplot. Then you can customize you axs using scales parameters.
imp <- importance(myref, class = NULL, scale = TRUE, type = 2)
dotplot(imp, scales=list(y =list(cex=2,
at = c(1,2),
col='red',
rot =20,
axs='i') ,
x =list(cex=2,col='blue')) )
You can extract the data needed to construct the plot out of myref and construct a plot with ggplot. By doing so you have more freedom in tweaking the plot. Here are some examples
library(ggplot2)
str(myrf)
str(myrf$importance)
data <- as.data.frame(cbind(rownames(myrf$importance),round(myrf$importance[,"IncNodePurity"],1)))
colnames(data) <- c("Parameters","IncNodePurity")
data$IncNodePurity <- as.numeric(as.character(data$IncNodePurity))
Standard plot:
(p <- ggplot(data) + geom_point(aes(IncNodePurity,Parameters)))
Rotate y-axis labels:
(p1 <- p+ theme(axis.text.y = element_text(angle = 90, hjust = 1)))
Some more tweaking (also first plot shown here):
(p2 <- p1 + scale_x_continuous(limits=c(3,7),breaks=3:7) + theme(axis.title.y = element_blank()))
Plot that looks like the varImpPlot (second plot shown here) :
(p3 <- p2+ theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_line(colour = 'gray', linetype = 'dashed'),
panel.background = element_rect(fill='white', colour='black')))
Saving to pdf is easy with ggplot:
ggsave("randomforestplot.pdf",p2)
or
ggsave("randomforestplot.png",p2)
p2
p3
Did I understood correctly, that you want to get texts charlie and bravo more left of the boundary of the plot? If so, here's one hack to archive this, based on the modification of the rownames used in plotting:
myrf = randomForest(alpha~bravo+charlie, data = mydata, importance = TRUE)
#add white spaces at the end of the rownames
rownames(myrf$importance)<-paste(rownames(myrf$importance), " ")
varImpPlot(myrf, type = 2)
The adj parameter in dotchart is fixed as 0 (align to right), so that cannot be changed without modifying the code of dotchart:
mtext(labs, side = 2, line = loffset, at = y, **adj = 0**, col = color,
las = 2, cex = cex, ...)
(from dotchart)
EDIT:
You can make another type of hack also. Take the code of dotchart, change the above line to
mtext(labs, side = 2, line = loffset, at = y, adj = adjust_ylab, col = color,
las = 2, cex = cex, ...)
Then add argument adjust_ylab to the argument list, and rename the function as for example dotchartHack. Now copy the code of varImpPlot, find the line which calls dotchart, change the function name to dotchartHack and add the argument adjust_ylab=adjust_ylab to function call, rename the function to varImpPlotHack and add adjust_ylab to this functions argument list. Now you can change the alignment of the charlie and bravo by changing the parameter adjust_ylab:
myrf = randomForest(alpha~bravo+charlie, data = mydata, importance = TRUE)
varImpPlotHack(myrf, type = 2,adjust_ylab=0.5)
From ?par:
The value of adj determines the way in which text strings are
justified in text, mtext and title. A value of 0 produces
left-justified text, 0.5 (the default) centered text and
right-justified text. (Any value in [0, 1] is allowed, and on most
devices values outside that interval will also work.)

Control font thickness without changing font size

I'm looking for a way to control the line thickness of text plotted in R without having the dimensions of the characters change. Here's an example (not using R):
The middle word has a thickness of twice the top, yet the dimensions are the same (so no scaling happened). The bottom word is actually two words: a red word overlain on a heavy white word, to create color separation (especially useful for annotating a busy plot).
Here's a set of commands I threw together to try and replicate the figure above:
png("font.png",width=1.02, height=1.02, units="in", res=150)
par(ps=10, font=1, bg="light gray", col="black", mai=rep(0.02,4), pin=c(1,1))
plot.new()
box()
text(0.5,0.85,"FONT",cex=1)
text(0.5,0.6,"FONT",cex=2)
text(0.5,0.3,"FONT",cex=2,col="white")
text(0.5,0.3,"FONT",cex=1,col="red")
text(0.5,0.1,"FONT",cex=1, font=2, col="white")
text(0.5,0.1,"FONT",cex=1, font=1, col="red")
dev.off()
giving:
So the effect is the same as changing the font-face to bold, but the size difference is not big enough to be noticeable when overlain. The par help page doesn't appear to have a specific setting for this. Anyone have any ideas?
Note changing size in ggplot2 doesn't produce the effect I want either, last time I checked.
You could try adding multiple versions of the text slightly shifted in a circular pattern,
library(grid)
stextGrob <- function (label, r=0.02, x = unit(0.5, "npc"), y = unit(0.5, "npc"),
just = "centre", hjust = NULL, vjust = NULL, rot = 0, check.overlap = FALSE,
default.units = "npc", name = NULL, gp = gpar(), vp = NULL){
let <- textGrob("a", gp=gp, vp=vp)
wlet <- grobWidth(let)
hlet <- grobHeight(let)
tg <- textGrob(label=label, x=x, y=y, gp=gpar(col="red"),
just = just, hjust = hjust, vjust = vjust, rot = rot,
check.overlap = check.overlap,
default.units = default.units)
tgl <- c(lapply(seq(0, 2*pi, length=36), function(theta){
textGrob(label=label,x=x+cos(theta)*r*wlet,
y=y+sin(theta)*r*hlet, gp=gpar(col="white"),
just = just, hjust = hjust, vjust = vjust, rot = rot,
check.overlap = check.overlap,
default.units = default.units)
}), list(tg))
g <- gTree(children=do.call(gList, tgl), vp=vp, name=name, gp=gp)
}
grid.stext <- function(...){
g <- stextGrob(...)
grid.draw(g)
invisible(g)
}
grid.newpage()
grid.rect(gp=gpar(fill="grey"))
grid.stext("Yeah", gp=gpar(cex=4))
There's a version using base graphics lurking in the archives of R-help, from which this is inspired.
Another option using a temporary postscript file, converted to a shape by grImport,
library(grImport)
cat("%!PS
/Times-Roman findfont
100 scalefont
setfont
newpath
0 0 moveto
(hello) show", file="hello.ps")
PostScriptTrace("hello.ps", "hello.xml")
hello <- readPicture("hello.xml")
grid.rect(gp=gpar(fill="grey"))
grid.picture(hello,use.gc = FALSE, gp=gpar(fill="red", lwd=8, col="white"))
I imagine something similar could be done with a temporary raster graphic file, blurred by some image processing algorithm and displayed as raster below the text.
You could try:
text(...,"FONT", vfont = c('serif','bold'))
Although I'm not sure how you'd do the third version of FONT.

Resources