Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right/left align subtitle position in plot

Tags:

plot

r

subtitle

How can I change the position of the subtitle in r "base" plot. Is there a special argument? I want to dynamically have the subtitle left or right aligned.

data

plot(mtcars$mpg,mtcars$qsec,xlab="",sub="I WANT TO\nBE RIGHT\nALIGNED")

plot data with desired output in red

enter image description here

EDIT

plottR <- function(...) {
    plot(...)
}

plottR(mtcars$mpg, mtcars$qsec, ylab="Y Must Center", xlab="X Must Center", main="Must center", sub="Must right-align",adj=1)

Can I input something to plottR so it only aligns the subtitle?

EDIT2

I just found out. I can evaluate the title() inside plot.

plottR(mtcars$mpg, mtcars$qsec, ylab="Y Must Center", xlab="X Must Center", main = "Must Center", title(sub ="Hey Only\nim right\ncool huh?",adj=1))
like image 247
Andre Elrico Avatar asked Oct 17 '22 02:10

Andre Elrico


1 Answers

You may use the par setting adj. From the help page:

A value of 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. (Any value in [0, 1] is allowed, and on most devices values outside that interval will also work.)

The drawback is that it influences the way text is justified for text, mtext, and title. Hence we have to break up the code in pieces if we want to leave e.g. the title and the Y-axis title untouched.

You could use the following code:

# store the current value of adj
adj.old <- par()$adj    # default is 0.5

# plot with the current value of adj
plot(mtcars$mpg, mtcars$qsec, xlab="")

# set adj to right-aligned and plot the subtitle
par(adj = 1)
title(sub = "I WANT TO\nBE RIGHT\nALIGNED")

# reset adj to previous value
par(adj = adj.old)

This generates the following graph:

enter image description here

like image 188
KoenV Avatar answered Oct 20 '22 23:10

KoenV