Plotting line graph with factors in R - r

I am working on this graph in R:
However as you see I am getting these solid dashes instead of nice lines. Here is the code I used to make this graph:
par(mar = c(5,5,2,5))
with(bedtimes, plot(trap, funestus, type="l", col="red3",
ylab=expression(italic(p))),
ylim=c(0,3))
par(new = T)
with(bedtimes, plot(trap, bed, pch=16, axes=F, xlab=NA, ylab=NA, cex=1.2))
axis(side = 4)
mtext(side = 4, line = 3, 'Proportion in bed')
polygon(bedtimes$bed,col=transp("gray", 0.3), border = NA)
And here is the dput of the data I am using:
(removed)
I realise that this is occurring because my x axis is a factor and not numeric. However, trying to change this (e.g. using as.POSIXct(paste0("2016-07-12",bedtimes$trap)) is causing me all sorts of problems, as I had to ake sure R plotted these factors in the correct order originally by using bedtimes$trap <- factor(bedtimes$trap, levels = bedtimes$trap)
How can I produce this same graph but with lines instead of these dashes?
I eventually want a graph that looks similar to this, to give you an idea (though not exactly the same):
Thank you!

As I said in comments, you can try to use the levels of your factor variable:
par(mar = c(5,5,2,5))
with(bedtimes, plot(as.numeric(trap), funestus, type="l", col="red3",
ylab=expression(italic(p))),
ylim=c(0,3))
par(new = T)
with(bedtimes, plot(as.numeric(trap), bed, type="l", axes=F, xlab="", ylab=NA, cex=1.2))
axis(4)
axis(side = 1, at=1:length(levels(bedtimes$trap)), levels(bedtimes$trap))
mtext(side = 4, line = 3, 'Proportion in bed')
polygon(bedtimes$bed,col="gray", border = NA)

Related

How to save plot drawn using with(plot()) to a variable in R?

I get the code for plotting with two y-axis from the following website:
https://www.r-bloggers.com/2015/04/r-single-plot-with-two-different-y-axes/
Here is my code after referencing the code in the link:
par(mar = c(5,5,2,5))
with(df, plot(Date, get(element), type="l", col="red3", ylab="beta_mkt"))
par(new = T)
with(df, plot(Date, NBER, type="l", axes=F, xlab=NA, ylab=NA, cex=1.2))
axis(side = 4)
mtext(side = 4, line = 3, "NBER")
This code prints out a plot, but I wanted to save this plot in a variable so I can reference it later. Anyone know how to achieve it?
Thanks.
Gin

placing legend outside a dynamically changing plot R

In my R code below, I have two situations each resulting in a different plot depending on S being larger OR smaller than 1. I was wondering how I can take out (move up) the current legend and put it above the plot at the same place for either of the resulting plots?
Note: Due to Y axis being on log-scale, I have used 10^par('usr')[4] but I need to add a number to 10^par('usr')[4] (i.e., (10^par('usr'))[4] + a number) such that "this number" puts the legend in the exact same place above either of the resulting plots?
Here is the R code:
S <- 0.25 ### !!! Change this to "24" and see how another plot will appear !!! ###
Ur <- c(0.25, 24, 16)
if(S>=1){
plot(1, 1, type = "n", xlim = c(0,1.5), ylim = c(1/3, 100), log="y", bty="n", ann=F, axes=F, xaxs="i")
axis(side=1, at = seq(0,1.5,.25),labels = c("0",".25",".5",".75","1","1.25","1.5"))
axis(side=2, at = c(1/3, 1, 3, 10, 30, 100),labels = c("1/3", "1", "3", "10", "30", "100"),las=1)
}else{
plot(1, 1, type = "n", xlim = c(0,1.5), ylim = c(.01, 3), log="y", bty="n", ann=F ,axes=F, xaxs="i")
axis(side=1, at = seq(0,1.5,.25),labels = c("0",".25",".5",".75","1","1.25","1.5"))
axis(side=2, at = c(.01, 1/30, 1/10, 1/3, 1, 3),labels = c("1/100", "1/30", "1/10", "1/3", "1", "3"),las=1)
}
legend(0, (10^par("usr"))[4], bquote(paste("Selected Prior: ",bold('PN'[10])," = ", .(round(S,3)))), ## Legend
pch = 21,cex=2,pt.bg="green", col="red", pt.cex=2.8, bty="n")
You can use the inset argument in legend.To do so, you need to use legend location as a word. In your case, "topleft". This way, you do not need to provide specific location based on your "y".
The inset argument allows you to offset the legend. In the present case, the y is offset by -0.03.
I also use par(xpd=TRUE)to expand the allowed plotting space. Finally, I also changed the font size to produce the following charts.
par(xpd=TRUE)
legend("topleft", legend=bquote(paste("Selected Prior: ",bold('PN'[10])," = ", .(round(S,3)))), ## Legend
pch = 21,cex=1,pt.bg="green", col="red", pt.cex=2, bty="n", inset=c(0,-0.03))

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.

Extending axes to encompass all data in R

I feel like this is a very basic question but I have spent a lot of time looking for an answer and haven't found one. So, if this is answered somewhere else I would love to be redirected rather than downvoted, please.
Anyway, my problem is that when I graph in R, often the y-axis will fail to extend to the end of my data. A sample graphic is below, where you can see that it would be better for the axis to go all the way to 30 rather than 20. However, submitting ylim = c(0,30) doesn't do anything and I cannot think of or find another command that would do the trick?
Here is a reproducible example. If ylim usually works then I am assuming something is breaking because of the aesthetic changes I've made?
set.seed(1)
x<-runif(1:1000, min=1, max=10)
hist(x, breaks=100, main=NA, axes=F, xlab = NA, ylab = NA)
axis(side = 1, tck= -.01, labels=NA)
axis(side = 2, tck=-.01, labels=NA)
axis(side = 1, lwd=0, line= -.4, cex.axis=1.4)
axis(side = 2, lwd=0, line=-.4, las=1, cex.axis=1.4)
mtext(side = 1, "Percent pathogenic bacteria", line = 2.5, cex=1.8)
mtext(side = 2, "Frequency", line = 2.5, cex=1.8)
Use ylim to specify the y axis range:
set.seed(3)
f <- function(y, ...)
hist(y, breaks=20, ...)
ylim <- range(pretty(ceiling(f(y <- rchisq(1000, 3), plot=FALSE)$counts/10)*10))
f(y, ylim=ylim) # versus f(y)

Replace X-axis with own values

I have a question regarding the command plot().
Is there a way to fully eliminate the x-axis and replace it with own values? I know that I can get rid of the axis by doing
plot(x,y, xaxt = 'n')
and then add an axis with
axis(side = 1 etc.)
However, when I add the axis, obviously it still refers to the data plotted as 'x'.
I would only like to plot the 'y'-values and add the x-axis my own in the sense of just "drawing" the x-axis with own values specified. Is there any way to do that?
The background of this question is that my two data frames differ in their length and therefore I cannot plot them.
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
You could set labels = FALSE inside axis(...) and then print the labels in a separate command using text(...). This option would allow you to rotate the text in case you need it.
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here

Resources