Improving the quality of a plot with postscript output chosen - r

I am still learning Sweave and R. I have below a sample code that reads in a data file and plots it. I am choosing the postscript option as I like ending up with an EPS file. There are a number of things that I would like to improve with the plot. Here is my code with my own comments for my own learning:
\documentclass[a4paper,12pt]{article}
\usepackage{Sweave} %%%%%%
\SweaveOpts{eps=TRUE}
\begin{document}
<<echo=FALSE, results=hide>>=
test.frame<-data.frame(ratio= c(0.0, 144.321, 159.407, 178.413, 202.557), value= c(0, 0.84, 0.8925, 0.945, 0.9975))
#
<<echo=FALSE,results=hide,eval=TRUE>>=
postscript('doudou.eps',
width=7, height=6,
colormodel="cmyk",
family = "ComputerModern",
horizontal = FALSE,
onefile=FALSE,
paper = "special",
encoding = "TeXtext.enc",
pagecentre=FALSE)
with(test.frame,plot(ratio, value, ylab= "Hello",
xlab="Wonderful",
type="o", # line and markers
bty="o", # box around graph
lty="solid", # solid line or put 1
lwd=3, # line width
pch=1, # or enclose symbol in quotes
cex=3, # size of markers
cex.lab=2, # label size
cex.axis=1.5, # axis annot size problem if big
cex.main=2, # main title size
xaxp=c(0, 200, 4), #c(x1, x2, n)
col=2, # plotting color
xlim=c(0,200),
yaxt = "n", #suppresses axis
main=" My curve"))
axis(2,seq(0,1, by=0.5), las=2,cex=3,cex.lab=2,cex.axis=1.5,cex.main=2)
dev.off()
#
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=0.8\textwidth]{doudou.eps}
\end{center}
\end{figure}
\end{document}
Some things that I would like to know more about an improve:
I have a boxed frame around the plot. How to control its line width?
I am using cex.axis=1.5for the axis annotation size. if I change it to say cex.axis=3 then the values on the x-axis get big and they overlap with the tickmarks. Is there a way to then place the x-axis values a bit lower further away from the plot?
The y-label Hello is truncated at the top of the H letter in the plot. How to fix this?
How to move either the x-label Wonderful or y-label Hello further away from the plot?
If we look at the plotted curve, the axes do not start at (0,0) though the initial values are (0,0) for the data set. How to control the axes so that they start at (0,0)?
Thanks a lot...

"I have a boxed frame around the plot. How to control its line width?"
box(lwd=3)
"I am using cex.axis=1.5 for the axis annotation size. If I change it to say cex.axis=3 , then the values on the x-axis get big and they overlap with the tickmarks. Is there a way to then place the x-axis values a bit lower further away from the plot?"
par(mgp=c(3,1.5,0) ) # second element is number of lines below the box for the labels
"The y-label Hello is truncated at the top of the H letter in the plot. How to fix this?"
# use par() to increase left margins
"How to move either the x-label Wonderful or y-label Hello further away from the plot?"
par( mgp=c(4,1.5,0) ) # First element in mgp vector
"If we look at the plotted curve, the axes do not start at (0,0) though the initial values are (0,0) for the data set. How to control the axes so that they start at (0,0)?"
..., xaxs="i", yaxs="i", ... # can be done in `par` or in the plot call
So the R code for the figure is below:
postscript('doudou.eps',
width=7, height=6,
colormodel="cmyk",
family = "ComputerModern",
horizontal = FALSE,
onefile=FALSE,
paper = "special",
encoding = "TeXtext.enc",
pagecentre=FALSE)
par( mgp=c(4,1.5,0), mai=c(1.5, 1.5, 1.5, .75) ) # using inches as the spacing unit
with(test.frame, plot(ratio, value, ylab= "Hello",
xaxs="i", yaxs="i",
xlab="Wonderful",
type="o", # line and markers
bty="o", # box around graph
lty="solid", # solid line or put 1
lwd=3, # line width
pch=1, # or enclose symbol in quotes
cex=3, # size of markers
cex.lab=2, # label size
cex.axis=3, # axis annot size problem if big
cex.main=2, # main title size
xaxp=c(0, 200, 4), #c(x1, x2, n)
col=2, # plotting color
xlim=c(0,200),
yaxt = "n", #suppresses axis
main=" My curve"))
axis(2,seq(0,1, by=0.5), las=2,cex=3,cex.lab=2,cex.axis=1.4, cex.main=2)
box(lwd=3)
dev.off()
Not pretty, but it does illustrate the control functions. Basically you need to spend more time on the help(par) page.

Related

How to make y axis labels horizontal but keep y-axis title parallel?

I would like to make my y axis labels horizontal, while keeping my y axis titles as parallel.
When I try inputting las=1 into the twoor.plot()argument, nothing happens. I have also tried ylas=1, y_las=1, lylas=1, rylas=1, and nothing happens. The only way I've been able to make my yaxis labels horizontal, is by using par(las=1), but then this makes my y-axis titles horizontal too, which I don't want...
This is my code so far:
par(las=1)
yFrequency <- c(0,20,40,60,80,100,120,140,160)
GS_class_labels <- c("<2", "2-4", "4-8", "8-16", "16-32", "32-64", "64-128", "128<")
twoord.plot(data=distribution,lx="Var1",ly="Freq", ry="cum_percentile",
main="B1 Surface Grain Size Distribution",
xlim=NULL,lylim=c(0,160),rylim=NULL,lwd=1.5,
lcol=1,rcol=2,xlab="Grain Size (mm)",lytickpos=yFrequency,
ylab="Frequency",ylab.at=NA,
rytickpos=NA,rylab="Percent Finer Than (%)",rylab.at=NA,
lpch=1,rpch=2,
type="b",xtickpos=NULL,xticklab=GS_class_labels,
halfwidth=0.4,axislab.cex=1.1,
do.first=NULL,xaxt="s", yticklab=yFrequency, cex.lab=1)
An alternative way to set the y axis labels parallel is as follows.
(1) Set both of the ylab and rylab from twoord.plot to empty.
(2) Use mtext and set the parameters accordingly.
Here is the code to do that. Because you don't provide the distribution data, I use iris data just to make it possible to generate the plot.
# Emptying both of ylab and rylab
twoord.plot(data = iris,lx="Sepal.Length",ly="Petal.Width", ry="Sepal.Width",
main="B1 Surface Grain Size Distribution",
xlim=NULL,lylim=c(0,160),rylim=NULL,lwd=1.5,
lcol=1,rcol=2,xlab="Grain Size (mm)",lytickpos=yFrequency,
ylab="",ylab.at=NA,
rytickpos=NA,rylab="",rylab.at=NA,
lpch=1,rpch=2,
type="b",xtickpos=NULL,xticklab=GS_class_labels,
halfwidth=0.4,axislab.cex=1.1,
do.first=NULL,xaxt="n",yaxt="n", #yticklab=yFrequency,
cex.lab=1)
# Assign the previous labels of ylab and rylab to the *text* parameter of *mtext*.
# side = 2 means the left side. side = 4 means the right side.
# las = 0 is the parallel style of the text.
# line shows the distance of the text from the y axis.
mtext(text = "Frequency", side = 2, las = 0, line = 2.5)
mtext(text = "Percent Finer Than (%)", side = 4, las = 0, line = 0.5)
The resulted plot:

How to adjust the space between 2 columns in a plot legend?

I want to have the plot legend for a pie chart as a single plot (6 graphics at a page - 5 plots, 1 legend). Now I have difficulties adjusting the space between the 2 columns.
I used the following code (by try and error):
#Colors
colors=c("blue","green","yellow","orange","red","purple","pink","grey")
legtext <- c("G","G*E","E","Source","Source*E",
"Table*E","Table*Block*E","Residual Error")
#Code for chart
pie3D(#data for pie
rooting1,
#specify labels vector
#labels=labels,
#specify labels size
labelcex=0.9,
#how much different pies go from each other
explode=0.1,
#height of chart
height=0.1,
#Main title
theta=pi/3,
#Colors
col=colors
)
#Code for legend
xcoords <- c(0.9,1,1.1,1.2)
secondvector <- (1:length(legtext))-1
textwidths <- xcoords/secondvector # this works for all but the first element
textwidths[1] <- 0
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths)
The plot I get is this: I want to remove the vertical lines and if possible, remove the rest of the chart as I only want to display the legend.
Legend I get:
Can anybody help me?
Add bty="n" to your legend:
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths,
bty="n")
As for the other question - how to get rid of the chart itself, this will take some fiddling. Basically, what you can do is to make an empty chart, but adjusting the xlim and ylim, as well as margins so that there is enough room for the legend:
par(mar=c(0.1,0.1,0.1,0.1)) # you don't need large margins
# but maybe you need more than 0.1
plot(NA, xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, xlab="", ylab="")
# this makes an empty plot
# you may need to change xlim and ylim (or the x and y of your legend)
# ... so that the legend would start from the left/upper corner

Legends overlapping the plots in Rstudio

I am trying to plot an image and then overlay a legend on its top. The legend is covering the plot and I am not able to adjust it using different parameters like cex, lty, etc.
plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
col=(cov16_2ms04h$binom_q<0.001)+1,
ylab="Haplotype B Count", xlab="Haplotype A Count")
abline(0,1,col="grey")
legend("topleft",c("No significant imbalance","Significant imbalance"),pch=c(10,10),col=c(1,2), cex = 0.5)
is giving me plot as:
But, I want something like:
Thanks,
have you tried enlarge the size of the plot before overlying a legend? I tried you legend code, the legend was perfect on the plot.
The problem is with R-studio because the size of the output plot is determined by the costumized size of the pane.
To plot the results directly to a pdf or a png file the following can be done.
# plotting directly on pdf or png - select the required one
pdf("my_plot.pdf", height=6, width=6)
png("my_plot.png", width = 4, height = 4,
units = 'in', res = 300)
plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
col=(cov16_2ms04h$binom_q<0.001)+1,
ylab="Haplotype B Count", xlab="Haplotype A Count")
abline(0,1,col="grey") # draw abline
legend("topleft",c("No significant imbalance","Significant imbalance"),
pch=c(1,1),col=c(1,2), cex = 0.75) # add legend
dev.off() # close the plot
The output then comes as:
Thanks,

Adding label to secondary axis in R

I have this code:
# Plotting everything
plot( p1, col= "lightgreen", xlim=c(-2.5,4.5), ylim=c(0, 700), main="Daily Total Precipitation for AR and Oct-May", xlab="ln(x)" , ylab="Frequency", xaxt = "n") # first histogram
plot( p2, col="red", xlim=c(-2.5,4.5), ylim=c(0, 700), xaxt = "n" , add=T)
# Adding in text labels on top of the bars
text(x, y, paste(round(percents,2),"%"), cex=0.50, pos=3, offset=0.3, col="black")
axis(side=1, at=breaks) # new x-axis
# parameter that needs to be set to add a new graph on top of the other ones
par(new=T)
plot(x, percents, xlim=c(-2.5,4.5), type="l", col="yellow", lwd=3.0, axes=F, ylab=NA, xlab=NA)
axis(side=4, at=seq(0,100,by=10), col="yellow", col.axis="yellow") # additional y-axis
mtext("Percent", side=4, col="yellow")
# legend settings
legend("topleft", c("AR", "Oct-May"), lwd=10, col=c("red", "lightgreen"))
Which produces this graph:
And I can't seem to figure out how to get the secondary y-axis label to show up in the correct position. Any help or suggestions is greatly appreciated.
Edit: Using RStudio.
One option is to specify the line argument to mtext(). In the example below I add a couple more lines to the right (side = 4) margin of the plot using par(), and then I draw three labels using mtext() at the default (line = 0), line 3 (line = 3), and line -3 (line = -3):
op <- par(mar = c(5,4,4,4) + 0.1)
plot(1:10)
mtext("line0", side = 4)
mtext("line3", side = 4, line = 3)
mtext("line-3", side = 4, line = -3)
par(op)
Note that line numbers increase away from the plot region and that negative line values move into the plot region, or to the left of the right boundary of the plot region.
It takes a little playing with the number of margin lines (as set in par(mar = x)) and which line you want to draw on using mtext(), but a little trial and error should get you what you want.
Note also that you don't need to specify integer values for the line argument. You can specify fractions of lines too: line = 2.5.

How to plot the value of abline in R?

I used this code to make this plot:
plot(p, cv2,col=rgb(0,100,0,50,maxColorValue=255),pch=16,
panel.last=abline(h=67,v=1.89, lty=1,lwd=3))
My plot looks like this:
1.) How can I plot the value of the ablines in a simple plot?
2.) How can I scale my plot so that both lines appear in the middle?
to change scale of plot so lines are in the middle change the axes i.e.
x<-1:10
y<-1:10
plot(x,y)
abline(a=1,b=0,v=1)
changed to:
x<-1:10
y<-1:10
plot(x,y,xlim=c(-30,30))
abline(a=1,b=0,v=1)
by "value" I am assuming you mean where the line cuts the x-axis? Something like text? i.e.:
text((0), min(y), "number", pos=2)
if you want the label on the x axis then try:
abline(a=1,b=0,v=1)
axis(1, at=1,labels=1)
to prevent overlap between labels you could remove the zero i.e.:
plot(x,y,xlim=c(-30,30),yaxt="n")
axis(2, at=c(1.77,5,10,15,20,25))
or before you plot extend the margins and add the labels further from the axis
par(mar = c(6.5, 6.5, 6.5, 6.5))
plot(x,y,xlim=c(-30,30))
abline(a=1,b=0,v=1)
axis(2, at=1.77,labels=1.77,mgp = c(10, 2, 0))
Similar in spirit to the answer proposed by #user1317221, here is my suggestion
# generate some fake points
x <- rnorm(100)
y <- rnorm(100)
# positions of the lines
vert = 0.5
horiz = 1.3
To display the lines at the center of the plot, first compute the horizontal and vertical distances between the data points and the lines, then adjust the limits adequately.
# compute the limits, in order for the lines to be centered
# REM we add a small fraction (here 10%) to leave some empty space,
# available to plot the values inside the frame (useful for one the solutions, see below)
xlim = vert + c(-1.1, 1.1) * max(abs(x-vert))
ylim = horiz + c(-1.1, 1.1) * max(abs(y-horiz))
# do the main plotting
plot(x, y, xlim=xlim, ylim=ylim)
abline(h=horiz, v=vert)
Now, you could plot the 'values of the lines', either on the axes (the lineparameter allows you to control for possible overlapping):
mtext(c(vert, horiz), side=c(1,2))
or alternatively within the plotting frame:
text(x=vert, y=ylim[1], labels=vert, adj=c(1.1,1), col='blue')
text(x=xlim[1], y=horiz, labels=horiz, adj=c(0.9,-0.1), col='blue')
HTH

Resources