Formatting X axis label in R for a specific condition - r

For the following sample code:
y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
days <- seq(as.Date("2015-2-25"), by="day", length=11)
n <- length(y)
x <- 1:n
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
lines(y)
I have the following chart:
What I want is when the month changes, I want to be able to add the month name below the day on the x axis. So in this example, when it becomes 01, it should show 01 Mar (March on a separate line)

It can happen if you do something like this:
Your data plus the month vector:
y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
days <- seq(as.Date("2015-2-25"), by="day", length=11)
#my addition
#contains the name of the month for where day == '01' else is blank
months <- ifelse(format(days, '%d')=='01', months(days) , '')
n <- length(y)
x <- 1:n
Solution:
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
lines(y)
Up to here is only your code. Now you need to add a new axis, set the axis colour to white and plot the month vector created above:
par(new=T) #new plot
par(mar=c(4,4,4,2)) #set the margins. Original are 5,4,4,2.
#I only changed the bottom margin i.e. the first number from 5 to 4
#plot the new axis as blank (colour = 'white')
axis(1, at=seq(1,11) ,labels=months, las=1, col='white')
The result looks like what you asked for:

Related

Add categorical grouping to scatter plot of continuous data in R?

Sorry if image 1 is a little basic - layout sent by my project supervisor! I have created a scatterplot of total grey seal abundance (Total) over observation time (Obsv_time), and fitted a gam over the top, as seen in image 2:
plot(Total ~ Obsv_time,
data = R_Count,
ylab = "Total",
xlab = "Observation Time (Days)",
pch = 20, cex = 1, bty = "l",col="dark grey")
lines(R_Count$Obsv_time, fitted(gam.tot2))
I would like to somehow show on the graph the corresponding Season (Image 1) - from a categorical factor variable (4 levels: Pre-breeding,Breeding,Post-breeding,Moulting), which corresponds to Obsv_time.
I am unsure if I need to plot a secondary axis or just add labels to the graph...and how to do each! Thanks!
Wanted graph layout - indicate season from factor variable
Scatterplot with GAM curve
You can do this with base R graphics. Leave off the x-axis in the original plot, and add an axis with the season labels separately. You can get indicate the season by overlaying polygons.
## Some bogus data
x = sort(runif(50,0,250))
y = 800*(sin(x/40) + x/100 + rnorm(50,0, 0.2)) + 500
FittedY = 800*(sin(x/40) + x/100)+500
plot(x,y, pch= 20, col='lightgray', ylim=c(300,2700), xaxt='n',
xlab="", ylab='Total')
lines(x, FittedY)
axis(1, at=c(25,95,155,215), tick=FALSE,
labels=c('PreBreed', 'Repro', 'PostBreed', 'Moulting'))
rect(c(-10,65,125,185), 0, c(65,125,185,260), 3000,
col=rainbow(4, alpha=0.05), border=NA)
If you are able to use ggplot2, you could add (or compute from time) another factor variable to your data-frame which would be your season. Then it is just a matter of using color (or any other) aesthetic which would use this season variable.
require(ggplot2)
df <- data.frame(total = c(26, 41, 31, 75, 64, 32, 7, 89),
time = c(1, 2, 3, 4, 5, 6, 7, 8))
df$season <- cut(df$time, breaks=c(0, 2, 4, 6, 8),
labels=c("winter", "spring", "summer", "autumn"))
ggplot(df, aes(x=time, y=total)) +
geom_smooth(color="black") +
geom_point(aes(color=season))

R: Combine a graph layout with a ggplot2 object and a gplots object

I want to have one figure with two plots, one of them is a ggplot2 object, and the second is a plot generated with gplots. For example combine the next two plots in a row:
library(ggplot2)
library(gplots) #For plotmeans
df = structure(list(age = c(14, 22, 35, 21, 88, 66, 14, 22, 35, 21),
values = c(22, 8, 1.9, 26.8, 32, 15.,1.9, 26.8, 32, 15.)),
.Names = c("age", "values"),
row.names = 1:10,
class = "data.frame")
ggplot(df, aes(values)) + geom_histogram()
plotmeans(df$values ~ df$age)
I tried grid, gridExtra, par and layout but w/o success.
Any idea how can I do so?
I found the next solution using gridBase:
(based on https://stackoverflow.com/a/14125565/890739)
library(gridBase) # To combine two plots
par(mfrow=c(1, 2))
plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport(c(1.8,1,0,1))
#Plot histogram
g1 <- ggplot(df, aes(values)) + geom_histogram()
print(g1,vp = vp1)
plotmeans(df$values ~ df$age)
Is there a simpler way?

Plot two xaxis in one plot?

This can be plotted very easily.
xvals <- c(5.5, 15.5, 25.5, 35.5, 45.5, 55.5, 65.5, 75.5, 85.5, 95.5)
yvals <- c(81, 63, 45, 27, 9, -9, -27, -45, -63, -81)
xn <- rep(1000, 10)
plot(xvals, yvals)
Both xvals and xn share the same yvals so I want to plot in one graph:
yaxis:
xaxis lower:xvals
xaxis upper:xn
I simply want to add xn to the same plot as an xaxis (the upper) axis(3).
Any idea on this!
Leave your code as it is up to plot(xvals, yvals). Then add the following:
#plot the first plot
plot(xvals, yvals)
#start new overlaid plot
par(new=TRUE)
#plot xn but remove the xaxis and the x label for now
plot(xn, yvals, xaxt='n', xlab='')
#add those at the top of the graph (3)
axis(3, xn)
#bonus. add this line to add a secondary xlabel on top
mtext(side = 3, line = 2, "xn")
Result:

Adding error bar to line graph

I am pretty new to R and I managed to create a graph using 'plot' but I forgot error bars and I would like to add them without redoing the whole thing. Does someone know a shortcut?
I calculated the mean by hand because the data set was so small.
Here is the raw data I used and the code to make the graph. I suppose I will need to have R calculate the mean and standard error, but when I try I cant get the graph to look the same.
# Pnem mean occurence each year
Plot9Pn <- c(46, 33, 28)
Plot11Pn <- c(20, 18, 10)
Plot14Pn <- c(34, 28, 26)
Plot15Pn <- c(57, 33, 12)
# Pram mean occurence each year
Plot9Pr <- c(30, 46, 95)
Plot11Pr <- c(8, 11, 14)
Plot14Pr <- c(10, 46, 46)
Plot15Pr <- c(15, 37, 110)
#hand calculated means across plots for each year- to be used in line graph
# Pn2009 <- 39.25
# Pn2010 <- 30.5
# Pn2011 <- 19
# Pr2009 <- 15.75
# Pr2010 <- 35
# Pr2011 <- 66.25
# Define 2 vectors
Pn <- c(39.25, 30.5, 19)
Pr <- c(15.75, 35, 66.25)
g_range <- range(0, Pn,Pr)
plot(Pr, type="o", pch=1, lty=1, col="red", ylim=g_range,
axes=FALSE, ann=FALSE)
lines(Pn, type="o", pch=2, lty=1, col="blue", ylim=g_range,
axes=FALSE, ann=FALSE)
# Make x axis using 2009-2011 labels
axis(1, at=1:3, lab=c("2009","2010","2011"))
# Create a title with a red, bold/italic font
title(main="Mean Yearly Pathogen Levels in Pilarcitos ", col.main="red", font.main=4)
# Label the x and y axes with dark green text
title(xlab="Year", col.lab=rgb(0,0.5,0))
title(ylab="# Positive", col.lab=rgb(0,0.5,0))
# Make y axis with horizontal labels that display ticks at
# every 4 marks. 4*0:g_range[2] is equivalent to c(0,4,8,12).
axis(2, las=1, at=8*0:g_range[2])
# Create box around plot
box()
# Create a legend at (1, g_range[2]) that is slightly smaller
# (cex) and uses the same line colors and points used by
# the actual plots
legend(1, g_range[2], c("P.ramorum","P. nemorosa"), cex=0.8,
col=c("red","blue"), pch=1:2, lty=1);
box()
I think you may have miscalculated the mean of Pn2010.
But if you also hand calculate the standard deviations
Pr.sd <- c(9.946, 16.553, 44.275)
Pn.sd <- c(15.903, 7.071, 9.309
You can add error bars with
arrows(x0=1:3, y0=Pr-Pr.sd, y1=Pr+Pr.sd,
code=3, angle=90, length=.1, col="red")
arrows(x0=1:3, y0=Pn-Pn.sd, y1=Pn+Pn.sd,
code=3, angle=90, length=.1, col="blue")
Here I just add +/- 1 sd. You can calculate them however you like. You might consider offsetting the points as it doesn't look particularly nice.
The arrows function is a base graphics function so it will work with the plotting code you already had. But to make things easier in the future, you'll probably want to look into use a plotting package like ggplot2 or lattice as both of those make plotting with multiple groups much easier and ggplot makes adding error bars easier as well.

R - Customizing X Axis Values in Histogram

I want to change the values on the x axis in my histogram in R.
The computer currently has it set as
0, 20, 40, 60, 80, 100.
I want the x axis to go by 10 as in:
0,10,20,30,40,50,60,70,80,90,100.
I know to get rid of the current axis I have to do this
(hist(x), .... xaxt = 'n')
and then
axis(side = 1) .....
But how do I get it to show the numbers that I need it to show?
Thanks.
The answer is right there in ?axis...
dat <- sample(100, 1000, replace=TRUE)
hist(dat, xaxt='n')
axis(side=1, at=seq(0,100, 10), labels=seq(0,1000,100))

Resources