Dates on x-axis; big dataset - r

I would like to plot a time series. I created an example to show how the graph should look like:
set.seed(1)
r <- rnorm(20,0,1)
z <- c(1,1,1,1,1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1)
data <- as.data.frame(na.omit(cbind(z, r)))
series1 <- ts(cumsum(c(1,data[,2]*data[,1])))
series2 <- ts(cumsum(c(1,data[,2])))
d1y <- seq(as.Date("1991-01-01"),as.Date("2015-01-01"),length.out=21)
plot_strategy <- function(series1, series2, currency)
{x11()
matplot(cbind(series1, series2), xaxt = "n", xlab = "Time",
ylab = "Value", col = 1:3, ann = TRUE, type = 'l',
lty = 1)
axis(1, at=seq(2,20,2), labels=format(d1y[seq(2,20,2)],"%Y"))
legend(x = "topleft", legend = c("TR", "BA"),
lty = 1,col = 1:3)
dev.copy2pdf(file= currency, width = 11.69, height = 8.27)}
plot_strategy(series1, series2,
currency= "all.pdf")
The actual dataset contains 6334 values. I therefore change the code to this:
axis(1, at=seq(2,6334,365), labels=format(d1y[seq(2,6334,365)],"%Y"))
But now, there are no values on the x-axis. Any suggstions?

Related

How can I make the y axis on a r plot display numbers in decimal format with commas?

I am running the following R code:
plot(datereal, casesimm8lock7,
type = "l", lwd = 1, col = "red",
main = "a Sensitivity to time delays: 8 month immunity",
xaxt = "n", xlab = "Month",
ylab = "Daily new cases", ylim = c(0,250000))
And I want the y-axis, which currently displays 50000 100000 150000 etc. to display 50,000 100,000 150,000 etc.
I am trying to use the scales package but haven't figured it out yet.
Start by making an empty plot with no y axis. Then plot the data.
Then plot the y axis with axis(2, ...). In order to have the labels formatted like the question asks for, use help("formatC").
# test data
datereal <- Sys.Date() - 10:0
casesimm8lock7 <- seq(0,250000, length.out = 11)
# the plot
plot(datereal, casesimm8lock7, type = "n", yaxt = "n")
lines(datereal, casesimm8lock7,
lwd = 1, col = "red",
main = "a Sensitivity to time delays: 8 month immunity",
xaxt = "n", xlab = "Month",
ylab = "Daily new cases", ylim = c(0,250000))
axis(2, at = seq(0, 250000, by = 50e3),
labels = formatC(seq(0, 250000, by = 50e3),
format = "d", big.mark = ","))
With package scales, it could be with either label_comma, like below, or label_number. Thse functions return a labeller function, to be applied to the vector of axis marks.
labeller <- scales::label_comma()
plot(datereal, casesimm8lock7, type = "n", yaxt = "n")
lines(datereal, casesimm8lock7,
lwd = 1, col = "red",
main = "a Sensitivity to time delays: 8 month immunity",
xaxt = "n", xlab = "Month",
ylab = "Daily new cases", ylim = c(0,250000))
axis(2, at = seq(0, 250000, by = 50e3),
labels = labeller(seq(0, 250000, by = 50e3)))

labeling nmds plot by column values in r

I ran metaMDS and want to plot and color code by a grouping based on certain data frame characters. In my original data frame, df$yr are years and df$2 are sites. I want to color by the years.
caltmds <- metaMDS(df[,3:12], k=3)
plot(caltmds, type = 'n')
cols <- c("red2", "mediumblue")
points(caltmds, col = cols[df$yr])
I also tried from this post:
scl <- 3
colvec <- c("red2", "mediumblue")
plot(caltmds, type = "n", scaling = scl)
with(df, points(caltmds, display = "sites", col = colvec[yr], pch = 21, bg = colvec[yr]))
text(caltmds, display = "species", cex = 0.8, col = "darkcyan")
with(df, legend("topright", legend = levels(yr), bty = "n", col = colvec, pch = 21, pt.bg = colvec))
Nothing plots
#DATA
df1 = mtcars
mycolors = df1$cyl #Identify the grouping vector
library(vegan)
m = metaMDS(df1)
x = scores(m) #Extract co-ordinates
plot(x, col = as.numeric(as.factor(mycolors)))

How to display legend without masking my spatial plot?

I get a problem for setting the position of legend and wonder if anyone can help.
I follow this example:
http://www.thisisthegreenroom.com/2009/choropleths-in-r/
My code is:
require(maps)
require(ggmap)
library(openxlsx)
rm(list = ls())
map("state", "Arizona")
setwd('M:/SCC/Q-Board')
PM25 <- read.xlsx("PM2.5_Emission_AZ_60 EIS emission sectors.xlsx", sheet = 'Emission_County', colNames = TRUE)
colors = c("#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77",
"#980043")
PM25$colorBuckets <- as.numeric(cut(PM25$PM25, c(0, 5, 10, 20, 30,40, 50)))
map("county",'Arizona', col = colors[PM25$colorBuckets], fill = TRUE,boundary = TRUE, resolution = 0,
lty = 1, projection = "polyconic")
title("PM2.5 Emission by county, 2011")
leg.txt <- c("<5", "5-10", "10-20", "20-30", "30-40", ">40")
legend("bottom", leg.txt, horiz = F, fill = colors,bty="n",title = 'Unit:1000 tons')
Then, the output figure was shown in below. I try to change the position by setting "top", "left"....
But the legend are still overlap with the figure.
Thank you for your help !
It seems to me that you simply run of out the plotting region. This is very common for spatial plot, which will often occupy a significant amount of your plotting domain. I would split the domain into two: one for spatial plot, the other for legend. The following code does this:
## a function to set up plotting region
## l: ratio of left region
## r: ratio of right region
split.region <- function(l, r) {
layout(matrix(c(rep(1, l), rep(2, r)), nrow = 1))
mai <- par("mai")
mai[2] <- 0.1
mai[4] <- 0
par(mai = mai)
}
# use 80% region for main image
# use 20% region for legend
split.region(4, 1)
## produce your main plot
image(x = 0:10/10, y = 0:10/10, matrix(rbinom(100, 1, 0.3), 10), bty= "n", xaxt = "n", yaxt = "n", ann = FALSE, main = "sample plot")
## set up 2nd plot, with nothing
plot(1:2, bty="n", ann=FALSE, xaxt = "n", yaxt = "n", col = "white")
## add your legend to your second plot
leg.txt <- c("<5", "5-10", "10-20", "20-30", "30-40", ">40")
## place legend at bottom left
legend("bottomleft", leg.txt, horiz = F, pch = 15, col = 1:6, bty="n", title = 'Unit:1000 tons', cex = 1.5)
Adjust l, r until you are satisfied.

plotting; adding own x-axis does not work

I would like to plot time-series data. To illustrate the dates on the x-asis, I first removed the values on the axis to then add my on axsis with the correct dates:
set.seed(1)
r <- rnorm(20,0,1)
z <- c(1,1,1,1,1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1)
data <- as.data.frame(na.omit(cbind(z, r)))
series1 <- ts(cumsum(c(1,data[,2]*data[,1])))
series2 <- ts(cumsum(c(1,data[,2])))
d1y <- seq(as.Date("1991-01-01"),as.Date("2015-01-01"),length.out=24)
plot_strategy <- function(series1, series2, currency)
{x11()
matplot(cbind(series1, series2), xaxt = "n", xlab = "Time",
ylab = "Value", col = 1:3, ann = TRUE, type = 'l',
lty = 1)
axis(1, at=as.POSIXct(d1y),labels=format(d1y,"%Y"))
title(ylab = "Value")
title(xlab = "Time")
legend(x = "topleft", legend = c("TR", "BA"),
lty = 1,col = 1:3)
dev.copy2pdf(file= currency, width = 11.69, height = 8.27)}
plot_strategy(series1, series2,
currency= "all.pdf")
However, the new x-axis doesn't show up. Any suggestions?
set.seed(1)
r <- rnorm(20,0,1)
z <- c(1,1,1,1,1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1)
data <- as.data.frame(na.omit(cbind(z, r)))
series1 <- ts(cumsum(c(1,data[,2]*data[,1])))
series2 <- ts(cumsum(c(1,data[,2])))
d1y <- seq(as.Date("1991-01-01"),as.Date("2015-01-01"),length.out=24)
matplot(cbind(series1, series2), xaxt = "n", xlab = "Time",
ylab = "Value", col = 1:3, ann = TRUE, type = 'l',
lty = 1)
axis(1, at=seq(2,20,2), labels=format(d1y[seq(2,20,2)],"%Y"))

Put one line chart and bar chart in one plot in R (Not ggplot)?

how to
Combine a bar chart and line in single plot in R (from different data sources)?
Say I have two data sources as:
barData<-c(0.1,0.2,0.3,0.4) #In percentage
lineData<-c(100,22,534,52,900)
Note that they may not be in the same scale.
Can I plot both barData and LineData in one plot and make them good looking ?
I cant use ggplot in this case so this is not a duplicated question..
Something like the following:
Maybe this helps as a starting point:
par(mar = rep(4, 4))
barData<-c(0.1,0.2,0.3,0.4) * 100
y <- lineData<-c(100,22,534,900);
x <- barplot(barData,
axes = FALSE,
col = "blue",
xlab = "",
ylab = "",
ylim = c(0, 100) )[, 1]
axis(1, at = x, labels = c("Julia", "Pat", "Max", "Norman"))
ats <- c(seq(0, 100, 15), 100); axis(4, at = ats, labels = paste0(ats, "%"), las = 2)
axis(3, at = x, labels = NA)
par(new = TRUE)
plot(x = x, y = y, type = "b", col = "red", axes = FALSE, xlab = "", ylab = "")
axis(2, at = c(pretty(lineData), max(lineData)), las = 2)
mtext(text="Lines of code by Programmer", side = 3, line = 1)
box()

Resources