Resizing parentheses in R expression - r

I would like my axis label to read something like
(m²)
with the height of the parentheses a little larger to match the superscript 2, but the parentheses nonetheless inline.
However, I either get parentheses that are too small, via something like
parse(text='group("(",m^{2},")")')
which yields
or parentheses that are too big and out-of-line, via something like
parse(text='bgroup("(",m^{2},")")')
which yields
Can I not do this in R?
Update:
As per the suggestion of user #42-, I've also tried scriptstyle. However, this makes the parenthesized text much smaller. It's particularly noticeable with neighboring text. For instance,
parse(text='Area~~(scriptstyle(m^{2}))')
would yield
I realize the workaround would be using something like
parse(text='scriptstyle(Area~~(m^{2}))')
which yields
and then manually upscaling font size to compensate, but is there a fix or alternative that won't require this kind of guesstimation?

Do you want;
plot(1,1, main=parse(text='scriptstyle( bgroup("(",m^{2},")"))') )
Or perhaps:
plot(1,1, main=parse(text='"("*scriptstyle(m^{2})*")"') )
A third altermative is to use "phantom()" which will reserve space equivalent to its argument. I found by experimentation that you could get parentheses that were not so "descend-ful" using:
plot(1,1, main=parse(text='"("*phantom(m^2)*")"') ,cex.main=1.6)
And then filling in the gap with:
title(main=expression(m^2) )
And it further twerking is needed, one can adjust the level of text relative to the "box" in units of text lines with title(main= <expression> , line= 2.5)
plot(1,1) ; title( main=expression(Area(phantom(" "))) ,cex.main=1.5, line=1.5)
title(main=expression(phantom('Area(')*m^2) ,line=1.5)

Related

text() in R on plot - how to keep on a single line without wrapping?

I often use R to run batch jobs that contain PDF outputs with scatter plots produced using a combination of plot() and points(), among other graphical functions. (I don't use ggplot2 much and would like to avoid using it for this question.)
When using the text() function in a plot in order to add text near a plotted symbol, I like to use the pos = 4 option to right-justify text next to say a symbol like pch = 23 (filled diamond). But I've noticed that sometimes the text will get wrapped as part of multiple lines, and other times it stays on a single line. Unfortunately when the lines are wrapped it causes text overlap problems. Why does text() sometimes wrap text on multiple lines?
Is there a way to force R to keep the text added to a plot from text() on a single line?
Here is my code:
text(x=data_frame_w_data_to_plot$x_axis_value,
y=data_frame_w_data_to_plot$y_axis_value, labels=data_frame_w_data_to_plot$text_to_plot, col="black", cex=1, pos=4)
Answering my own question here. Found the text string of "\n" just happened to be in one of the cells, and simply used gsub() to slightly modify this cell. This solved the problem. Learn from my mistake. :)
data_frame_w_data_to_plot$text_to_plot <- gsub("\n", " ", data_frame_w_data_to_plot$text_to_plot)

What is a good way to fit text inside a plotting area with ggplot2 using a pre-defined width for the text?

Here's an example of a problem:
example=data.frame(x1=c(1,4.1,7),x2=c(4,7.1,10),
y1=c(1,1,5),y2=c(2,2,6),text=c('Example','A Bigger Example','little.lite'))
example$xmid = (example$x1+example$x2)/2
example$ymid = (example$y1+example$y2)/2
ggplot()+geom_rect(data=example,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=text))+
geom_text(data=example,aes(x=xmid,y=ymid,label=text))
The output looks like this:
I've tried adjusting the size of labels by using the number of characters in the string, but it doesn't take into account spacing and kerning of different characters in non-monospace fonts. For example,
example$text_size=24/nchar(as.character(example$text))
ggplot()+geom_rect(data=example,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=text))+
geom_text(data=example,aes(x=xmid,y=ymid,label=text,size=text_size))+
scale_size_continuous(range=c(4,8))
The output then looks like this:
While the widths of the text in the lower boxes are the same, the text width of the string with many l's and t's is smaller. Is there any way to calculate the spacing in advance so that the width of all of the different characters into account?
Per suggestion by #Tyler Rinker, I used the strwidth function instead of nchar.
example$text_size2=24/strwidth(as.character(example$text))
ggplot()+geom_rect(data=example,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=text))+
geom_text(data=example,aes(x=xmid,y=ymid,label=text,size=text_size2))+
scale_size_continuous(range=c(4,8))
The end result looks like this:

italics and normal text in a main plot title

I am plotting a graph in R but the italics function and it is being pretty frustrating under the main title:
Mapped territories of different C. austriacus individuals at the Far Gardens coral reef site
Any help would be appreciated.
You didn't give any information about your data but if the problem is italics in the title, maybe this code could help:
plot(rnorm(100), main = substitute(paste(italic('p value'), " = 0.01")))
See also this question.
Personally I think using paste to construct plotmath expression is "ugly"; This is an alternative the more clearly demonstrates "clean" use of expression:
plot(rnorm(100),main=expression( italic(p~value) == 0.01 ))
The other reason to use expression is that it will be accepted by Lattice functions whereas the substitute approach will not:
xyplot(1~1,main=substitute( paste(italic('p value'), " = 0.01" )))
#Error in paste(italic("p value"), " = 0.01") :
# could not find function "italic"
It would succeed if expression() were used inside the substitute call but it's excess baggage in that instance. I complained to Deepayan Sarkar once and his response was that substitute returns an unevaluated "call" rather than a true 'expression'.
I think other users have answered this, but I found it not so cut and dry, and built off of their input because it gets tricky for long titles like the one in your example.
Here is the cleanest line of code I could conjure for combined italic/normal texts, using a generic plot... let me know how it works for your data (or anyone who reads this and finds it doesn't work with certain graphs, inbox me, I enjoy learning and would rather share than just store it in my noggin)
plot(1:10, main = expression('Mapped territories of different '*italic(C.~austriacus)*' individuals at the Far Gardens coral reef site'))
Now, to line break with expression or like terms that allow italicized or superscript/subscript text (other than simple labels), you can use the atop function to evenly break apart super long labels. One may prefer to use the preview app for final editing and labels, but if you want to stick to R for everything, you can use the following example:
plot(1:10, main = expression(atop('Mapped territories of different '*italic(C.~austriacus), ' individuals at the Far Gardens coral reef site')))
which gives:
plot with long mixed title
Thanks to #42-

How to make dashed / dotted / dash-dotted line in octave?

I'd like to create monochrome diagram/graph in octave using plot command.
That is why I'd like make different lines of graphs with using line style, for example dashed/dotted/dash-dotted styles. Standard plot suggests several styles for line, but none of them looks like listed variants.
EDIT-1:
Standard plot styles are inapplicable for my case: such styles as ":", "-.", "--" don't work, octave draws solid lines in any case. Furthermore, diamonds and squares (d and s options) are ugly and disproportionate big. May be it will be helpful information: I'm using Octave under Windows.
EDIT-2: For example, such command plot(A(:,1),A(:,2),"-.dk") gives me such (inapplicable !!!) figure
More specifically I want something like this (in part of line style)
(Picture from article: McCallum and K. Nigam. 1998. A comparison of event models for Naive Bayes text classification. In Proceedings of AAAI-98 Workshop on Learning for Text Categorization)
These can be set with the FMT argument of plot. Basically, these seem to be your options (see the manual entrey on line styles):
"-" solid lines
":" points
"-."dash followed by dot
"--" dashed
"none" no line (only markers)
There is also the option "." for dots but this is for the actual data points, not the line. So to recreate your picture, something like the following should work
plot (multinominal, "-dk", "MarkerFaceColor", "k")
hold on;
plot (mv-bernoulli, ":sk", "MarkerFaceColor", "k")
The syntax may look a bit strange but here's how to read it. For -dk, - is for solid line, d for diamond shaped marker, and k for black colour (b would be for blue). On :sk, it's dotted line and square shaped marker in black colour.
See the section on the manual for advanced plotting.
EDIT: see the comments below. This may not work in very old versions of Octave.
Well, I found a simple solution by myself (using Google ;))
For gaining monochrome diagram/graph with a different style of lines in Octave, we don't need to use plot's styles like "--" or "-." (because they do not work).
Just one thing we need is the command print. Monochrome figures can be created for example in the eps format:
print -deps "diagram.eps"
This gives me quite a nice picture:
I had the same problem and I think that the solution to make visible the line style is changing the linewidth. Many linestyles are not distinguished when the default linewidth value is used (which is 1).
Try the following code and see if it works:
x = ( 0:0.4:10 );
f = sin(x) .* exp(-4 .* x);
g = sin(x);
plot(x,f,'r:','linewidth',5,x,g,'-.','linewidth',2)
print(gcf,"PlotSimple.pdf")

Spacing in axis label when using expression(paste(...))

Consider the following example:
plot(c(2,4,6)~c(1,2,3),xlab="x",
ylab=expression(paste('flux (g ',CO[2]~m^{-2}~h^{-1},')')))
Obviously I want a full space between "g" and "CO", but for some reason I get a smaller (with some labels even zero) space in the graph label.
The problem is even more obvious, if I do it like this:
plot(c(2,4,6)~c(1,2,3),xlab="x",
ylab=expression(paste('flux (g C',O[2]~m^{-2}~h^{-1},')')))
Am I doing something wrong? Is there a way to fix the spacing or even a better way to create labels with lots of sub/superscripts and greek letters?
In all likelihood you are getting a typographically correct "space", in the font your OS uses for non-serif display. You can change fonts or you can insert blank space that is sufficient to hold a particular character string with plotmath phantom():
plot(c(2,4,6)~c(1,2,3),xlab="x",
ylab=expression(paste('flux',phantom(x),'(g ',CO[2]~m^{-2}~h^{-1},')')))
Or as #baptiste points out this can be done without plomath paste using ordinary plotmath separators because a tilde in a true R expression gets handled as a "space":
ylab=expression(flux*phantom(x)*(g~CO[2]~m^{-2}~h^{-1})))

Resources