Do we need to call dev.off() after creating a pdf file? - r

When I call dev.off() my pdf gets created but I get the following message "null device 1".
I don't get any warning when I remove dev.off and my pdf gets created so why do I need to call dev.off for?
plot(x # independent variable (population_density)
, y # dependent variable (case_fatality_rate)
, main = "ScatterPlot - Case Fatality Rate vs Population Density Per Square Mile" # chart
title
, xlab = "Population Density Per Square Mile" # x-axis label
, ylab = "Case Fatality Rate" # y-axis label
, pch = 19 # point shape (filled circle)
, frame = T # surround chart with a frame
, xlim = c(0, 1200), ylim = c(0, 3)
)
model <- lm(y ~ x, data = dataset) # compute the linear model
abline(model, col = "blue") # draw the model as a blue line
hist(y # depandant variable (case_fatality_rate)
, main = "Histogram - Case Fatality Rate Frequency" # chart title
, xlab = "Case Fatality Rate",
ylab = "Frequency",
col = "#f0ffff",
breaks = 15,
freq = FALSE,
prob = TRUE,
xlim = c(0.5,2.5),
ylim = c(0.0,2.0)
)
lines(density(y, adjust=1.2), col="blue", lwd=2)
grid(nx = NA, ny = NULL,
lty = 1, col = "gray", lwd = 1)
dev.off()

Related

RDA triplot in R- plot only numeric explanatory variables as arrows; factors as centroids

I ran a distance-based RDA using capscale() in the vegan library in R and I am trying to plot my results as a custom triplot. I only want numeric or continuous explanatory variables to be plotted as arrows/vectors. Currently, both factors and numeric explanatory variables are being plotted with arrows, and I want to remove arrows for factors (site and year) and plot centroids for these instead.
dbRDA=capscale(species ~ canopy+gmpatch+site+year+Condition(pair), data=env, dist="bray")
To plot I extracted % explained by the first 2 axes as well as scores (coordinates in RDA space)
perc <- round(100*(summary(spe.rda.signif)$cont$importance[2, 1:2]), 2)
sc_si <- scores(spe.rda.signif, display="sites", choices=c(1,2), scaling=1)
sc_sp <- scores(spe.rda.signif, display="species", choices=c(1,2), scaling=1)
sc_bp <- scores(spe.rda.signif, display="bp", choices=c(1, 2), scaling=1)
I then set up a blank plot with scaling, axes, and labels
dbRDAplot<-plot(spe.rda.signif,
scaling = 1, # set scaling type
type = "none", # this excludes the plotting of any points from the results
frame = FALSE,
# set axis limits
xlim = c(-1,1),
ylim = c(-1,1),
# label the plot (title, and axes)
main = "Triplot db-RDA - scaling 1",
xlab = paste0("db-RDA1 (", perc[1], "%)"),
ylab = paste0("db-RDA2 (", perc[2], "%)"))
Created a legend and added points for site scores and text for species
pchh <- c(2, 17, 1, 19)
ccols <- c("black", "red", "black", "red")
legend("topleft", c("2016 MC", "2016 SP", "2018 MC", "2018 SP"), pch = pchh[unique(as.numeric(as.factor(env$siteyr)))], pt.bg = ccols[unique(as.factor(env$siteyr))], bty = "n")
points(sc_si,
pch = pchh[as.numeric(as.factor(env$siteyr))], # set shape
col = ccols[as.factor(env$siteyr)], # outline colour
bg = ccols[as.factor(env$siteyr)], # fill colour
cex = 1.2) # size
text(sc_sp , # text(sc_sp + c(0.02, 0.08) tp adjust text coordinates to avoid overlap with points
labels = rownames(sc_sp),
col = "black",
font = 1, # bold
cex = 0.7)
Here is where I add arrows for explanatory variables, but I want to be selective and do so for numeric variables only (canopy and gmpatch). The variables site and year I want to plot as centroids, but unsure how to do this. Note that the data structure for these are definitely specified as factors already.
arrows(0,0, # start them from (0,0)
sc_bp[,1], sc_bp[,2], # end them at the score value
col = "red",
lwd = 2)
text(x = sc_bp[,1] -0.1, # adjust text coordinate to avoid overlap with arrow tip
y = sc_bp[,2] - 0.03,
labels = rownames(sc_bp),
col = "red",
cex = 1,
font = 1)
#JariOksanen thank you for your answer. I was able to use the following to fix the problem
text(dbRDA, choices = c(1, 2),"cn", arrow=FALSE, length=0.05, col="red", cex=0.8, xpd=TRUE)
text(dbRDA, display = "bp", labels = c("canopy", "gmpatch"), choices = c(1, 2),scaling = "species", arrow=TRUE, select = c("canopy", "gmpatch"), col="red", cex=0.8, xpd = TRUE)
#JariOksanen thank you for your answer. I was able to use the following to fix the problem
text(dbRDA, choices = c(1, 2),"cn", arrow=FALSE, length=0.05, col="red", cex=0.8, xpd=TRUE)
text(dbRDA, display = "bp", labels = c("canopy", "gmpatch"), choices = c(1, 2),scaling = "species", arrow=TRUE, select = c("canopy", "gmpatch"), col="red", cex=0.8, xpd = TRUE)

Non-numeric argument to binary operator in R: Survival Analysis

I'm not sure why I get this error. I get the graph after, sure, but I don't know what is causing the error.
plot(survfit(Surv(time,DEATH_EVENT) ~ hypertension, data=HF), main = "Hypertension Survival Distributions", xlab = "Length of Survival",ylab="Probability of Survival",col=c("blue","red")) +
legend("topright", legend=c("Absent", "Present"),fill=c("blue","red"),bty="n")
Error in plot(survfit(Surv(time, DEATH_EVENT) ~ hypertension, data = HF), :
non-numeric argument to binary operator
This, however, works wonders:
ggsurvplot(survfit(Surv(time,DEATH_EVENT) ~ hypertension, data=HF),
data = HF,
censor.shape="|",
conf.int = FALSE,
ggtheme = theme_bw())
If you alter some of your parameters, it should work as expected:
plot(survfit(Surv(time, DEATH_EVENT) ~ hypertension, data = HF), main = "Hypertension Survival Distributions", xlab = "Length of Survival", ylab = "Probability of Survival", col = c("blue","red"))
legend(x = 1, y = 1, legend = c("Absent", "Present"), col = c("blue","red"), lty = 1)
NB. change legend(x = 1 to "whatever the max x axis value is", e.g. legend(x = 1000 to place the legend in the top right.

Add calculated mean value to vertical line in plot in R

I have created a density plot with a vertical line reflecting the mean - I would like to include the calculated mean number in the graph but don't know how
(for example the mean 1.2 should appear in the graph).
beta_budget[,2] is the column which includes the different numbers of the price.
windows()
plot(density(beta_budget[,2]), xlim= c(-0.1,15), type ="l", xlab = "Beta Coefficients", main = "Preis", col = "black")
abline(v=mean(beta_budget[,2]), col="blue")
legend("topright", legend = c("Price", "Mean"), col = c("black", "blue"), lty=1, cex=0.8)
I tried it with the text command but it didn't work...
Thank you for your advise!
Something along these lines:
Data:
set.seed(123)
df <- data.frame(
v1 = rnorm(1000)
)
Draw histogram with density line:
hist(df$v1, freq = F, main = "")
lines(density(df$v1, kernel = "cosine", bw = 0.5))
abline(v = mean(df$v1), col = "blue", lty = 3, lwd = 2)
Include the mean as a text element:
text(mean(df$v1), # position of text on x-axis
max(density(df$v1)[[2]]), # position of text on y-axis
mean(df$v1), # text to be plotted
pos = 4, srt = 270, cex = 0.8, col = "blue") # some graphical parameters

How to add legend in a 3D scatterplot

I have a 3D scatter plot that looks like this
and the code associated with it is as follows
nr = c(114,114,1820,100,100)
acc = c(70.00,45.00,98.89,82.00,74.90)
ti = c(25.00,87.50,0.25,41.40,51.30)
label = c(1, 2, 3, 4, 5)
data = data.frame(nr, acc, ti, label)
library(scatterplot3d)
scatterplot3d(data$nr, data$acc, data$ti, main = "3D Plot - Requirements, Accuracy & Time", xlab = "Number of requirements", ylab = "Accuracy", zlab = "Time", pch = data$label, angle = 45)
Now, I want to add a legend to the bottom right to indicate what those symbols mean
tech <- c('BPL','W','RT','S','WSM')
For instance, the triangle stands for BPL, + for RT and so on
You can try this:
library(scatterplot3d)
# define a plot
s3d <-scatterplot3d(data$nr, data$acc, data$ti, main = "3D Plot - Requirements, Accuracy & Time",
xlab = "Number of requirements", ylab = "Accuracy", zlab = "Time", pch = data$label, angle = 45)
# add a legend
legend("topright",s3d$xyz.convert(18, 0, 12), pch = data$label, yjust=0,
# here you define the labels in the legend
legend = c('BPL','W','RT','S','WSM'), cex = 1.1
)

How do I make well separated mirrored histogram in R

I have this RData here. I want to plot a mirrored histogram that looks like this figure where each line is well separated. I have these codes below which seems to work, but the lines are clumped together and are not well separated. How can I separate the lines? I did try all these options:
"p" for points,
"l" for lines,
"b" for both,"p" for points,
"h" for 'histogram' like
Additionally, I also want to add plus and minus above and below zero respectively as shown in the example figure.
Here is my code:
load("rdata.rdata")
# Now plot
tiff(
filename = paste0("Mirrored plot of ", sample.name) ,
width = 4,
height = 2,
pointsize = 6,
units = 'in',
res = 300
)
plot(
pos$coverage,
type = 'h',
# type= 's',
ylim = c(-20, 20),
# col='blue',
col = 'deepskyblue2',
# ylab=expression ("Number of aligned reads" ~ (10^-3)),
ylab = "",
xlab = paste0("Aligned with ", aligned.with),
xaxt = 'n',
# main=paste0("Coverage of mapped " , sample.name," reads")
# ylab to re-align the y-axis legend
)
title(
ylab = expression ("Number of aligned reads" ~ (10 ^ -3)),
line = 2,
cex.lab = 1.2,
family = "Calibri Light"
)
# plot the coverage on the negative strand
#neg coverage ; getting (10^-3) so easy to plot
lines(neg$coverage,
type = 'h',
# type='s',
# col='red'
col = 'darkorange3')
l <- length(pos$position)
axis(1,
at = floor (seq(
from = 1, to = l, by = l / 10
)),
labels = floor (seq(
from = head(pos$position, n = 1) - 0,
to = tail(pos$position, n = 1),
by = l / 10
)))
dev.off()

Resources