Output Stem and Leaf Plot to Image - r

I'm trying to output a Stem and Leaf plot in R as an image. I'm not sure if there's a nice library which can accomplish this but below is some of the code I've tried.
jpeg(filename="stem.jpeg",width=480,height=480, units="px",pointsize=12)
plot.new()
tmp <- capture.output(stem(men, scale = 1, width = 40))
text( 0,1, paste(tmp, collapse='\n'), adj=c(0,1), family='mono' )
dev.off()
This above code resulted in the data being saved, but it looks very blurry and the plot gets cut off pretty badly. When adding a histogram to an image, R seems to do a good job to scale everything to fit in the size of the image.
jpeg(filename="stem.jpeg",width=480,height=480,
units="px",pointsize=12)
stem(men, scale = 1, width = 40)
dev.off()
This created the image but had no content within it.
Any ideas? Thanks!

That's because stem and leaf plots produce text not images. You can save the text as follows using the sink command: http://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html
sink(file=“Stem.txt”)
stem(men, scale = 1, width = 40)
sink(file=NULL)
unlink("stem.txt")

To export a stemplot as graphics, you can use a vector graphics format, such
as .eps, .pdf, or .emf. For example, a windows metafile:
win.metafile("stem.wmf", pointsize = 10)
plot.new()
tmp <- capture.output(stem(mtcars$mpg))
text(0,1,paste(tmp,collapse='\n'),family='mono',adj=c(0,1))
dev.off()

Related

Fitting a long list of studies in Metafor Forestplot to make it readable

I'm trying to do a forest plot using metafor::forest. The problem is that because I have over 100 studies the output is unreadable because the rows blend together and overlap unless I choose a very small font (in which case you also can't read it).
Any ideas on how to plot this so that the font is large enough to be read without having all rows overlap?
Here's the code I'm using:
library(metafor)
res <- rma(yi, vi, data=dat)
par(mar = c(6, 6, 6, 6))
forest(res, addpred=T, header=TRUE, atransf=exp, at=log(c(.05, 0.5, 5, 15)), xlim=c(-5,5), ylim=c(-3,190), cex=.75)
This is the output
The only way it doesn't overlap is with cex = .05, but it is of course impossible to see anything:
I do not known the library nor the data, and cannot reproduce your example, but, for case, try using another output device:
png("file.png" , width = 480, height = 4000)
plot(runif(100))
dev.off()
Then see result file in current (getwd()) directory.

How can I re-scale a forest plot in RStudio?

I am trying to reproduce the plot from the example dataset in the robumeta package in R Studio. While the script works (as expected), I can only see a fraction of the graph. When I increase the size of the window, I get to see more but never the whole thing because apparently, my computer screen is too small and there is no option to scroll up or down. Is there a way to re-scale the forest plot or to print it to pdf (with several pages, if needed)?
Here's the code from package description file:
install.packages("robumeta")
library(robumeta)
data(oswald2013.ex1)
oswald_intercept <- robu(formula = effect.size ~ 1, data = oswald2013.ex1, studynum = Study, var.eff.size = var.eff.size, rho = 0.8, small = TRUE)
forest.robu(oswald_intercept, es.lab = "Crit.Cat", study.lab = "Study",
"Effect Size" = effect.size, # optional column
"Weight" = r.weights) # optional column
png(filename, height, width, pointsize)
#your plot code
dev.off()
in which you play around with the height, width, and pointsize parameters should allow you to save the graph to your desired view size. It won't save as a pdf, but rather a png, which should be ok if your goal is just to view the entire forest plot.

Define margins of PDF used for boxplot rendering

When I render a boxplot on a PDF device in R there is a large white space besides the graph, especially at the top that i intent to reduce.
My script is basically just:
data <- read.csv("input.csv")
pdf(file="output.pdf", width=4, height=5)
boxplot(data, xlab="input graphs", ylab="vertex count")
This leads to something like:
where the grey outline indicates the end of the document.
I tried to use the par attributes "mar" and "mai" as described in https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/par.html but it had no effect.
boxplot(data, mar=c(0,0,0,0=, mai=c(0,0,0,0))
Do you have an advice how I can gain whitespace control? I want to have zero outer whitespace as the generated graph will be used in a Latex environment that provides sufficient spacings on its own. I am using Ubuntu as OS.
Define mar right after pdf. Try this as an example
pdf(file = "test.pdf", width = 5, height = 5)
par(mar = c(5, 5, 0.05, 0.05))
set.seed(42)
plot(rnorm(20))
dev.off()

small plot with no margins - border with line width (lwd) equal to 1 not visible

I've been trying to make some very tiny line graphs using base plotting functions, but am coming unstuck when trying to add a thin border.
This is via RGui on Windows 7, saving a png from the plot window.
Here's my code:
dev.new(width=1.3,height=0.3)
par(mar=c(0,0,0,0))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1))
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
Everything is fine until I try to add a box with a line width of 1, giving:
box(lwd=1)
Now I can solve this by increasing the line width to 2, but this seems a bit of a hack.
box(lwd=2)
Using rect like rect(1,0,10,1) doesn't seem to give me an appropriate solution either, with the bottom and right borders not being visible.
Have you considered giving mar a small non-zero value:
dev.new(width=0.3,height=0.3)
par(mar=c(0.01,0.01,0.01,0.01))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1))
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
box(lwd=1)
I admit I haven't quite figured out what the end-game might be, but when I do an interactive "stretch" of that very small screen-object, it does result in an all-around border.
I do recognize that I am on a Mac and saving this to a pdf file and converting it to a png file for SO-inclusion may not be precisely reproducible on a Linux or Windows device.
Another solution base in grid and gridBase package. The idea is to replace the box by grid.rect.
Use gridBase to get the base viewport
Introduce some offset (viewport y ) to show the bottom line
Reduce the width of the viewport to show the right line.
Here my code:
library(gridBase)
sp <- baseViewports()
vp <- sp$plot
vp$width <- unit(0.999,'npc')
vp$y <- unit(0.001,'npc')
pushViewport(vp)
grid.rect(gp=gpar(fill=NA))
upViewport(1)
EDIT thanks to #baptiste, you can simply get the same result using only grid.rect:
library(grid)
grid.rect(width = unit(0.999,'npc'),
y = unit(0.5001, "npc"),
gp=gpar(fill=NA))
To answer my own question thanks to #baptiste's tip-off, this is a device dependent issue due to RGui. If the image is saved directly out to file using png everything works as intended. E.g.:
dev.new(width=1.3,height=0.3)
# repeat from here onwards only for png call below
par(mar=c(0,0,0,0))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1),bty="n")
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
box(lwd=1)
Saving out to png from the "R Graphics" window gives my original stuffed up image:
Going directly to file using png like:
png("textbox_direct.png",width=116,height=27)
# take code block from above
dev.off()
...gives the correct result:

heatmap in R how to resize columns labels?

I have a data.matrix that is approximately 4000 rows and 100 columns. I am doing a heatmap of the data like:
data<-heatmap(data_matrix,Rowv=NA,Colv=NA,col=cm.colors(256),scale="column",margins=c(5,10))
But the problem that I got is that the labels that appear in the column are too grouped, so it is impossible to visualize them correctly. How I can resize the heatmap so I can see the values of the labels of the column? I tried to print it in pdf, but it only appears a black stripe.
Thanks
I am including a figure of the heatmap, the portion that I want to see are the labels that are in the right part, but they are too close together.
First of all it's better to put your output directly to a PDF file - you may use other image formats but PDF is the best because it is a vector output and you can zoom as much as you want:
pdf("Your-file.pdf", paper="a4", width=8, height=8)
Then it's better to use pheatmap( = pretty heatmap) package. It makes really better heatmaps with a color key besides your heatmap. Finally although the pheatmap() function tries to reduce the label size while you have many rows, but it fails for really large number of rows. So I use the code below for really high - but not too high - number of rows:
library(pheatmap)
library(gplots)
if (nrow(table) > 100) stop("Too many rows for heatmap, who can read?!")
fontsize_row = 10 - nrow(table) / 15
pheatmap(table, col=greenred(256), main="My Heatmap", cluster_cols=F,
fontsize_row=fontsize_row, border_color=NA)
You may change fontsize_col for the column labels. You have many interesting options like display_numbers to have the values inside the cells of your heatmap. Just read ?pheatmap.
This is an example generated by the default parameters of pheatmap() command:
Finally note that too many rows are easy to read on a display, but useless for print.
In Rstudio you can easily resize the graphic window, same holds for Rgui. Alternatively, if you save the plot to file you can use a bigger size for your graphics, e.g. bigger width and height when calling pdf or png.
You can use cexRow = and cexCol =.
You can get more information into ??heatmap.2
# Row/Column Labeling
margins = c(5, 5),
ColSideColors,
RowSideColors,
cexRow = 0.2 + 1/log10(nr),
cexCol = 0.2 + 1/log10(nc),
labRow = NULL,
labCol = NULL,
srtRow = NULL,
srtCol = NULL,
adjRow = c(0,NA),
adjCol = c(NA,0),
offsetRow = 0.5,
offsetCol = 0.5,
colRow = NULL,
colCol = NULL
If you use pheatmap (https://www.rdocumentation.org/packages/COMPASS/versions/1.10.2/topics/pheatmap) you can spread out those labels by adjusting the cellheight parameter.
If you are doing this in R notebook, even though the entire heat map will not display in your output window when you run the code, when you save the heat map to your computer using the filename parameter, pheatmap will automatically calculate the optimal size for the output file so that your entire heatmap will be displayed in your output file. If this size is not to your liking you can adjust using width and height parameters, but it is unlikely you will want to do this.

Resources