italics and normal text in a main plot title - r

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-

Related

Formatting line breaks when using superscripts in tmap legend

I am trying to create a map with the tmap showing the population density. Therefore, I want the legend title of the map to be "Population density in n\ [people per km^2]". This map is the closest I have gotten to my desired final result.
Now, as you see, I manage to insert a line break but somehow the last "]" jumps all to the right and the title is cut half off in the first line. I think the latter is a problem I can solve by myself, but I don't find a solution to get rid off the former problem.
To create this map, I used the following code
tm_polygons("Pop_dens",title=expression(paste("Population density \n[people per km"^"2","]")),breaks=c(0,50,100,500,1000,3000,5000,25000),border.alpha = 0)+
tm_shape(border_plateau)+
tm_polygons(alpha=0)+
tm_scale_bar(breaks=c(0,10,20,50,100),position = c(0.56,0.04))+
tm_compass(position = c(0.4,0.04))+
tm_legend(legend.position=c(0.71,0.11))
How can I remove the space (ergo make it left-binding)?
I am familiar with making new lines in the legend using \n and pasting expressions using expression(paste(..)), but combining both doesn't seem to work.
One option would be to use:
title=expression(atop("Population density","(people per km"^2*")"))
Although the space between lines may be excessively large
I faced the same problem and solved it by using HTML tags with the package ‘htmltools’:
title=paste('Line 1', br('Line 2'))

Initializing and customizing an autoplot r-project object

My head is getting sore from me banging it so much.
I have a time-series that I've converted into an xts object w/ 7 variables. Now I'm trying to plot 4 of them, all price indices, on the same graph. I used autoplot (from the ggfortify package) to initialize the graph, and this is where the trouble begins.
Autoplot doesn't seem to work unless I give it at least one variable to plot. That's fine, but the two customizations I want for the variable -- its color and line type -- seem to have no effect.
But once I create the plot this way, I have little trouble adding the other 3 variables by adding geom_lines. Here's sort of what the code looks like:
p <- autoplot(foo.xts,xlab="Year",
ylab="Price Index",
columns="Variable1",linetype=4) # the linetype accomplishes nothing
p <- p + geom_line(aes(y="Variable2", color="green", linetype="solid"
# etc. for the other 2 variables
p # The 3 added variables do get the selected colors & line types.
But how can I customize the line for the first variable?
Then there's another problem in that I can't get a legend to appear. Here's how I'm trying to do that:
p <- p + scale_color_discrete(
name="Price Indices",
breaks=c("Variable1", "Variable2", "Variable3", "Variable4"),
labels=c("Index 1", "Index 2", "Index 3", "Index 4"))
This seems to accomplish nothing.
One thing I'd add is that in my various experiments trying to get the legend to work, I've sometimes gotten two sets of keys: one for colors and one for line types. This is obviously not what I'm after.
If someone could help me with this, I'd be forever in your debt!
I spent yesterday away from the computer, and when I returned in the evening fixed the problems. Here's how:
Stopped using autoplot. It's a classic case of hand-holding that throws you over the cliff. In other words, it automatically formats the plot in ways that are difficult (impossible?) to customize. Instead, ggplot makes the initial plot.
Since I'm making a series of plots, moved all the shared features to a separate, preamble section. This section creates a base plot, sets the x-axis variable (the date of the observation), labels the x-axis, and formats its tick marks. It also sets up standardized colors, line styles, and shapes to be used by all the "production" plots.
To set up the standardized elements, it uses scale_color_manual, etc. Each one has to be identical in all respects except those that are unique to its specific aesthetic attribute. E.g., scale_color_manual uses values like "red" whereas scale_linetype_manual uses values like "solid." Each manual setting includes the following elements: legend.title*, values, labels, and guide = guide_legend()*. (Items marked with * must be identical, otherwise you'll get different legends for each one.) For each plot, the actual legend title is first stored in a variable, legend.title, and then used in all the manual scale setting. This way the manual settings can be moved to the common section, but each plot has is own unique title for its legend.
3A. Actually, I was wrong about this. I was thinking LaTeX, where most things are evaluated where they appear at execution time. So a scale_color_manual statement at the start could change later on just by changing the value of legend.title. But in R, things are evaluated sequentially, and changing legend.title after the scale_color_manual statement is executed will have no effect. I worked around this by defining several variables in the preamble (e.g., one with the colors I'm using) and then using these variables in the various source_x_manual statements. This way, the only thing that change is the legend title.
Then each production plot starts by copying the base plot, labeling the y-axis, and then adds the geometric objects that it needs.
This approach has several advantages. 1) It modularizes the plotting so that problems are easier to isolate and solve, and most solved problems in the preamble section are solved for all plots. 2) It standardizes the plots, ensuring that their common features are formatted identically. 3) It reduces each production plot to a few statements; since this is the unique part for each plot, creating a new style of plot becomes relatively easy. 4) The value added by autoplot becomes minimal because this approach, separating shared elements in a preamble, compensates by isolating reusable code and the preamble, once debugged, allows much more fine-grain customization.
If you have any questions, please feel free to ask.

How to create a dyraph with multiple x-axis labels?

I'm working with a lot of rank data that would benefit from a way to simultaneously display its respective year on the x-axis. For example, I want to create the following graph adapted from the dygraph gallery:
Note how the rank information (red arrow) for a particular weekend (green arrow) are both displayed on the x axis.
I know this might not be possible with dygraphs now, at least it wasn't available in these demos, so I guess my follow up question would be are there any plans to make this possible (how about in the [r] {dygraph} package)? Apparently a plotter called flot can do this.
UPDATE 1
If indeed this feature does not exist yet, then the following, although potentially obvious to Dygraph developers, is a thought for accomplishing the task easily (perhaps I'm wrong). At first I thought it would be necessary to provide input data of the form shown in Table A
However such input is a major deviation from the existing Dygraph parser model who expects one abscissa. Such suggests that a modification to the parser to accept a "Dual Label" option, requiring that both labels be contained in a single abscissa element as in Table B, would be easier. Thereafter, with the option specified, the parser would manage CSV as it usually would with the exception that it is now "bin cognizant" and detects division between labels 1 and 2 by use of an acceptable delimiter (in this case a single quotation mark - maybe not the best choice) and divisions between label 1 abscissa elements by name change. Behind the scenes each point gets its unique x coordinate and the "Dual Label" option causes the dygraph to visually scoot up a couple pixels to accommodate an extra label. Not sure how to handle full zoomed scrolling put simply leaving a label 1 element centered until an adjacent label 1 element comes on screen is an option.
Dygraphs rule!
There's no simple way to do this with dygraphs now. As you say, there's a fairly deep assumption that there's only a single x-axis.
Your best bet would be to either modify the existing legend plugin to do this, or to create a new plugin which renders just the "Weekend 1", "Weekend 2" line. While the plugins API isn't official yet, it is at least somewhat documented.
If you get this to work, please share your code!

Replace a plot under the par() function of R

There should be an easy way to deal with this, but I don't know. I'm plotting multiple figures with the par(mfrow=c(5,5)) subplot function of R (i.e. 25 figures). After plotting 10 figures say for example I've done something wrong with the 11th plot, now if I want to plot it again using plot function it takes the space for 12th subplot which means the whole subplot structure changes. I know that par(new=TRUE) would let me re-plotting on the top of the 11th figure, but what if the revised plot is so different that overlapping doesn't work? The idea is to erase the 11th figure and then plot it all over again. How about changing the 1st plot after plotting all 25 figures??
It is possible to use the screen family of functions, though I confess to not being an aficionado of them. As you would hope against, it is only to be used exclusive of par(mfrow=c(5.5)) or even layout(...).
Having said that, it is entirely possible to redraw over a screen. For instances:
split.screen(c(5,5))
for (scr in 1:25) {
screen(scr)
par(mar=rep(0,4)+0.1)
plot(0)
}
screen(7)
par(bg='white') # necessary for some display types
erase.screen()
plot(2)
(This is certainly not a beautiful example, but it is functional.)
Notice the explicit setting of the background color (bg) to white; with some displays where transparency is assumed, not doing this will appear to have no affect (that is, erase.screen() will do nothing).
Having said that, there are many modern and near-modern graphing functions/libraries/packages that do things that this package does not support. I have not tested this with image-capturing mechanisms (such as sandwiching things in png(file="...") and dev.off()). Caveat emptor!

Unwanted bold-face while putting multiple ggplot charts in the same file

I don't know if you have seen some unwanted bold-face font like picture below:
As you see the third line is bold-faced, while the others are not. This happens to me when I try to use ggplot() with lapply() or specially mclapply(), to make the same chart template based on different data, and put all the results as different charts in a single PDF file.
One solution is to avoid using lapply(x, f) when f() is a function that returns a ggplot() plot, but I have to do so for combining charts (i.e. as input for grid.arrange()) in some situation.
Sorry not able to provide you reproducible example, I tried really hard but was not successful because the size of code and data is too big with several nested functions and when I reduced complexity to make a reproducible example, the problem did not happen.
I asked the question because I guessed maybe someone has faced the same experience and know how to solve it.
My intuition is that it's not actually being printed in bold, but rather double-printed for some reason, which then looks bold. This would explain why it doesn't come up with a simpler example. Especially given your mention of nested functions and probably other complicated structures where it's easy to get an off-by-one or similar error, I would try doing something where you can see exactly what's being plotted -- perhaps by examining the length() of the return value from apply().
Changing the order of elements of the vector, so that the order of the elements in the key is different, may also help. If you consistently get the bold-face on the last element, that also tells you a little bit more about where something is going wrong.
As #Dinre also mentioned, it could also be related to your plotting device. You can try out changing your plotting device. I have my doubts about this though, seeing as it's not a consistent problem. You could also try changing the position of the key, which depending on your plotting device and settings, may move you in or out of a compression block, thus changing which artifacts crop up.
Reproducible example and a solution may be as follows:
library(ggplot2)
d <- data.frame(x=1:10, y=1:10)
ggplot(data = d, aes(x=x, y=y)) +
geom_point() +
geom_text(aes(3,7,label = 'some text 10 times')) +
geom_text(data = data.frame(x=1,y=1),
aes(7,3, label = 'some text one time'))
When we try to add a label by geom_text() manually inserting x and y do not shorten the data. Then same label happen to be printed as many times as the number of rows our data has. Data length may be forced to 1 by replacing data within geom_text().

Resources