I have quick question, I do I take these type of data and loop through and put each datapoint into a new plot?
quantity <- c(3,5,2)
names(quantity) <- c("apples","bananas", "pears")
plot(quantity)
png(file = Path, width =4, height =4, units = "in", res = 600)
par(mfrow = c(3,3)
for (i in names(quantity)){
print(i)
plot(x = quantity[i], y = names(quantity)[i])
}
dev.off()
Related
I am trying to save 10 plots in PNG format, but it only shows me one plot. How can I fix the code below?
par(mfrow = c(3,4))
png(filename = "roc.png", width = 1200, height = 1200)
roc = list()
for(id in 1:10)
{
roc[[id]] = ModelCross[[id]]$roc
roc_ = ModelCross[[id]]$roc
coords_<- coords(roc_, best.method="closest.topleft") ## "youden", "closest.topleft"
par(pty = "s")
plot(roc_,col = "blue",print.thres="best", print.thres.best.method="closest.topleft")
print(paste0('roc',id))
}
dev.off()
I have created 3 rows with 3 figures each and would like to centre the last 2 figures to achieve visual representativity since they are aligned to the left side of my multiple plot. Is there any way of doing that without modifying the size of the graphs?
dat=read.csv("r1new.csv", header=TRUE, sep=",", dec="."); dat
par(mfrow=c(4,3))
par(mar=c(4,4,2,2))
############################################### WC 0.1 ###############################################
res.lm1 = lm(dat$wc_10_1~dat$m_wc_10_1, data=dat)
res.lm2 = lm(dat$wc_10_3~dat$m_wc_10_3, data=dat)
res.lm3 = lm(dat$wc_10_5~dat$m_wc_10_5, data=dat)
res.res1 = resid(res.lm1)
res.res2 = resid(res.lm2)
res.res3 = resid(res.lm3)
plot(dat$m_wc_10_1 [1:1731], res.res1,
ylab="Residuals",
xlab="modelled water content, 0.1 m",
main="",
xlim=c(0.05,0.55), ylim=c(-0.25,0.15),
type="p",
col="blue",
pch=16)
points(dat$m_wc_10_3 [1:814],res.res2, col="green3",pch=16)
points(dat$m_wc_10_5 [1:1768],res.res3, col="red",pch=16)
abline(0, 0, col="gold3", lwd=2)
You should check out layout. You need to define a matrix that shows the order and placement of graphs. Then these are filled in according to number. I believe the following example is approximately what you are looking for:
M <- matrix(rep(1:12, each = 2), nrow = 4, ncol = 3*2, byrow = T)
M[4,] <- c(0,10,10,11,11,0)
M
png("testplot.png", width = 6, height = 7, units = "in", res = 200)
layout(M)
layout.show(11)
op <- par(mar = c(3,3,0.5,0.5))
for(i in seq(11)){
plot(rnorm(10), rnorm(10))
}
par(op)
dev.off()
Just a quick question: I want to remove plot elements. Such as col, main etc.
I am adding a picture to you can understand better.
https://hizliresim.com/XMQr0R
str(nr)
kmncluster <- kmeans(na.omit(nr), centers = 10, iter.max = 500, nstart = 5, algorithm="Lloyd")
knr <- ndvi
knr[] <- kmncluster$cluster
values(knr) <- kmncluster$cluster
mycolor <- c("#fef65b","#ff0000", "#daa520","#0000ff","#0000ff","#00ff00","#cbbeb5",
"#c3ff5b", "#ff7373", "#00ff00", "#808080")
par(mfrow = c(1,2))
plot(ndvi, col = rev(terrain.colors(10)), main = 'Landsat-NDVI')
plot(knr, main = 'Unsupervised classification', col = mycolor )
dev.off()
I just want to keep the picture. I don't want to see any other information.
I have list of data and list of plots which I want two write to xlsx file (each element to separate sheet). Example data:
require(ggplot2)
require(data.table)
n <- 10
N <- 100
dtList <- lapply(1:n, function(x) data.table(sample(1e6, N), 1:N))
names(dtList) <- 1:n
plots <- lapply(dtList, function(x) ggplot(x, aes(y = V1, x = V2)) + geom_line())
Currently I use openxlsx, but it is quite slow for multiple plots:
require(openxlsx)
wb <- createWorkbook()
modifyBaseFont(wb, fontSize = 10)
writeXlsx <- function(x, sName) {
addWorksheet(wb, sName, gridLines = FALSE)
writeData(wb, sName, x = x, xy = c(1, 1))
print(plots[[sName]])
insertPlot(wb, sName, width = 19, height = 9, dpi = 200, units = "cm",
startRow = 2, startCol = 5)
}
system.time(
sapply(seq_along(dtList), function(x) {
writeXlsx(dtList[[x]], names(dtList)[[x]])
})
) # ~ 17.00 sek
openXL(wb)
How could I increase speed of this? Is there a better package to accomplish this?
One options is to use simpler graphics. For example, changing plots to base graphics, like:
plots <- lapply(dtList, function(x) plot(x$V2, x$V1, type = 'l'))
reduces the xlsx creation time to ~0.72 seconds vs ~7.78 seconds (original code works now faster than before), that is around 10 times faster.
When ggplot graphics are needed, I modified insertPlot function to accept this type of object and save it to file without needing to print in R session (using ggsave):
insertggPlot <- function(wb, sheet, width = 6, height = 4, xy = NULL,
startRow = 1, startCol = 1, fileType = "png",
units = "in", dpi = 300, PLOT) {
od <- getOption("OutDec")
options(OutDec = ".")
on.exit(expr = options(OutDec = od), add = TRUE)
if (!"Workbook" %in% class(wb)) stop("First argument must be a Workbook.")
if (!is.null(xy)) {
startCol <- xy[[1]]
startRow <- xy[[2]]
}
fileType <- tolower(fileType)
units <- tolower(units)
if (fileType == "jpg") fileType = "jpeg"
if (!fileType %in% c("png", "jpeg", "tiff", "bmp"))
stop("Invalid file type.\nfileType must be one of: png, jpeg, tiff, bmp")
if (!units %in% c("cm", "in", "px"))
stop("Invalid units.\nunits must be one of: cm, in, px")
fileName <- tempfile(pattern = "figureImage",
fileext = paste0(".", fileType))
ggsave(plot = PLOT, filename = fileName, width = width, height = height,
units = units, dpi = dpi)
insertImage(wb = wb, sheet = sheet, file = fileName, width = width,
height = height, startRow = startRow, startCol = startCol,
units = units, dpi = dpi)
}
Using this, reduces time to ~2 sek.
I have made a loop for making multiply plots, however i have no way of saving them, my code looks like this:
#----------------------------------------------------------------------------------------#
# RING data: Mikkel
#----------------------------------------------------------------------------------------#
# Set working directory
setwd()
#### Read data & Converting factors ####
dat <- read.table("Complete RING.txt", header =TRUE)
str(dat)
dat$Vial <- as.factor(dat$Vial)
dat$Line <- as.factor(dat$Line)
dat$Fly <- as.factor(dat$Fly)
dat$Temp <- as.factor(dat$Temp)
str(dat)
datSUM <- summaryBy(X0.5_sec+X1_sec+X1.5_sec+X2_sec+X2.5_sec+X3_sec~Vial_nr+Concentration+Sex+Line+Vial+Temp,data=dat, FUN=sum)
fl<-levels(datSUM$Line)
colors = c("#e41a1c", "#377eb8", "#4daf4a", "#984ea3")
meltet <- melt(datSUM, id=c("Concentration","Sex","Line","Vial", "Temp", "Vial_nr"))
levels(meltet$variable) <- c('0,5 sec', '1 sec', '1,5 sec', '2 sec', '2,5 sec', '3 sec')
meltet20 <- subset(meltet, Line=="20")
meltet20$variable <- as.factor(meltet20$variable)
AllConcentrations <- levels(meltet20$Concentration)
for (i in AllConcentrations) {
meltet.i <- meltet20[meltet20$Concentration ==i,]
quartz()
print(dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
key = list(points = list(col = colors[1:2], pch = c(1, 2)),
text = list(c("Female", "Male")),
space = "top"), col = colors, pch =c(1, 2))) }
I have tried with the quartz.save function, but that just overwrites the files. Im using a mac if that makes any difference.
When I want to save multiple plots in a loop I tend to do something like...
for(i in AllConcentrations){
meltet.i <- meltet20[meltet20$Concentration ==i,]
pdf(paste("my_filename", i, ".pdf", sep = ""))
dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
key = list(points = list(col = colors[1:2], pch = c(1, 2)),
text = list(c("Female", "Male")),
space = "top"), col = colors, pch =c(1, 2))
dev.off()
}
This will create a pdf file for every level in AllConcentrations and save it in your working directory. It will paste together my_filename, the number of the iteration i, and then .pdf together to make each file unique. Of course, you will want to adjust height and width in the pdf function.