How to add threshold line when there are multiple graphs? - r

I am using a function which plots two graphs on the same picture. I want to add threshold line to the first graph and a different threshold on the second graph. I am using abline() function to do so. chr6 comes with a library as an example.
install.packages("GenWin")
library(GenWin)
chrom_num = 6
jpeg(filename = paste(chrom_num, ".jpg", sep=""), width = 1200, height = 800)
chr = splineAnalyze(chr6$Fst, chr6$Position, plotRaw = 1, plotWindows = 1, method = 4)
abline(0.3, 0, col = "green")
abline(6, 0, col = "green")
Both threshold lines show up on the second graph. How to prevent this? In other word is there a way to direct to which graph I am adding something?

If you want to add something, I think it would be better to make graphs by yourself from the analyzed data, chr (almost all code is picked out from splineAnalyze). This approach would enable you to customize the graph.
analyzed_data <- chr # All you need to do is changing these lines and data and col names of 1st plot()).
smoothness <- 100 # default value
jpeg(filename = paste("file_name", ".jpg", sep=""), width = 1200, height = 800)
par(mfrow = c(2,1))
# 1st graph
plot(Fst ~ Position, chr6, xlab = "Position (bp)", ylab = "Raw values")
with(analyzed_data,
lines(x = seq(0, max(rawSpline$x), by = smoothness),
y = predict(rawSpline, seq(0, max(rawSpline$x), by = smoothness)), col = "red")
)
abline(0.3, 0, col = "green")
# 2nd graph
with(analyzed_data,
plot(x = (windowData$WindowStop - windowData$WindowStart)/2 + windowData$WindowStart,
y = windowData$Wstat, xlab = "Position (bp)", ylab = "Spline Wstat", pch = 19)
)
abline(6, 0, col = "green")
dev.off()
Of course, you can do it using splineAnalyze(..., plotRaw = 1, plotWindows = 1, ...) and adding the lines.
jpeg(filename = paste("file_name2", ".jpg", sep=""), width = 1200, height = 800)
chr = splineAnalyze(chr6$Fst, chr6$Position, plotRaw = 1, plotWindows = 1, method = 4)
abline(6, 0, col = "green") # draw on 2nd panel
layout(matrix(c(2,1), ncol = 1)) # refocus 1st panel
par(new = T)
plot(Fst ~ Position, chr6, ann = F, type = "n", axes = F) # reproduce the coordinates
abline(0.3, 0, col = "green") # draw on 1st panel
dev.off()

Related

Improving graph quality while exporting in r

I have written following code for comparing between to different variables over a period. The code works fine but only problem is when i output the file as "jpeg" the lines are not smooth and my arrow is not as smooth as i like it to be in other words the graph feels very low quality. But when i output it as "pdf" i get smooth lines and graph is of higher quality. But pdf files are high in file size and i need to insert these graphs in word file. I find it relatively easy to append jpeg into the word file. So is it possible to improve image quality while being in jpeg format. I tried using res argument in jpeg() but it doesnot output the graph as it is displayed in the rstudio.
I will appreciate the help. Thanks!
code:
library(shape)
library(Hmisc)
### samples ######
xaxs = seq(1,30,length=30)
precip = sample(200:800, 30)
ero = sample(0:10, 30, replace = T)
#########
svpth = getwd()
nm = "try.jpeg"
jpeg(paste0(svpth,"/",nm), width=950 , height =760, quality = 200, pointsize =15)
par(mar= c(5,4,2,4), oma=c(1,1,1,1))
plot(xaxs,precip, type = "p", pch=15, col="green", ylim = c(200,1000),
xlab = "Year" , ylab = "", cex.main=1.5, cex.axis=1.5, cex.lab=1.5)
lines(xaxs, precip,lty =1, col="green")
# xtick<-seq(0,30, by=1)
# axis(side = 1, at=xtick, labels = FALSE )
minor.tick(nx=5, ny=2, tick.ratio=0.5, x.args = list(), y.args = list())
mtext("Depth (mm)", side = 2, line = 2.7, cex = 1.5)
par(new=T)
plot(xaxs, (ero * 10), ylim = c(0,max(pretty(range((ero * 10))))+20), type = "p", pch=20, cex=1.5, col="red", axes = F, xlab = "", ylab = "")
lines(xaxs, (ero * 10),lty =2, col="red")
axis(side = 4, at=pretty(range((ero * 10))), cex.axis = 1.5)
# mtext("Erosion (t/ha/yr)", side = 4, line = 2.2, cex = 1.5)
mtext(expression(paste("Erosion (t ", ha^-1, yr^-1, ")")), side = 4, line = 2.7, cex = 1.5)
legend("topleft", legend = c("Precipitation","Erosion"), lty = c(1,2), pch = c(15,20), col = c("green","red"), cex = 1.6, bty = "n")
####arrow
Arrows(7, 85, 11, 90,lwd= 1.1)
Arrows(26, 85, 21, 90, lwd= 1.1)
txt = "High erosion rates in \nwheat-planting years"
xt = 16
yt = 85
text(xt, yt, labels = txt, family="serif", cex = 1.23)
sw = strwidth(txt)+1.4
sh = strheight(txt) +6
frsz = 0.38
rect(xt - sw/2 - frsz, yt - sh/2 - frsz, xt + sw/2 + frsz, yt + sh/2 + frsz-1)
# legend(15,80, legend = c("High erosion rates in \nwheat-planting years\n"),
# xjust = 0.5, yjust = 0.5)
dev.off()
It didn't use base R, but this makes an svg, which is smaller than a jpeg and will create some beautiful images. MS Word has no problems with svg, either.
The svg-- 18 kb; the jpeg-- 592 kb for the same image.
Use if it works, if not, well, perhaps someone else could use it? This won't show in the plot pane in RStudio, it will show in the viewer pane.
After the code, I have an image of saving the plot in the viewer pane in RStudio.
library(plotly)
df = data.frame("Year" = xaxs, "Depth" = precip, "Erosion" = ero *10)
p = plot_ly(df) %>%
add_trace(x = ~Year, y = ~Depth,
type = 'scatter', mode = 'lines', # to have both the points and lines use 'lines+markers'
name = "Depth",
line = list(shape = "spline", # smooth the curves in the lines (not that effective with lines+markers)
color = "green")) %>%
add_trace(x = ~Year, y = ~Erosion,
mode = 'lines',
name = "Erosion",
yaxis = "y2", # second y axis
line = list(dash = 'dash', # dash the lines
shape = "spline", # smooth the curves in the lines
color = "red")) %>% # without "lines+markers" spline will smooth out the points of the line
add_annotations(inherit = F, # add the arrows at the top of the plot
x = list(12, 18), # this is plot coordinates
y = list(800, 800),
ax = list(-60, 60), # this is pixels
ay = list(10, 10),
showarrow = T,
text = "") %>%
add_annotations(inherit = F, # add the textbox at the top of the plot
x = 15, y = 800,
ax = 0, ay = 0,
showarrow = F,
bordercolor = 'black',
text = "High erosion rates in\nwheat-planting years") %>%
layout(yaxis2 = list(overlaying = "y", side = "right", # add labels
title = paste0("Erosion (t ",
"ha<sup>-1</sup>",
"yr<sup>-1</sup>",
")")),
yaxis = list(title = "Depth (mm)"),
legend = list(x = .1, y = 1000),
margin = list(r = 80)) # right margin space for label
To save it, add the functionality. The icons at the top of the plot in the image at the end won't show until you hover over them. I think you may find that if you use this, the height/width specifications you have aren't the best fit anymore.
(p <- p %>% config( # save the plot; add a save function to the plot
toImageButtonOptions = list(
format = "svg",
filename = "try",
width = 950,
height = 760)) # end config
) # end () for print simo object assignment
The plot. The width and height in this image are 950 x 550.

R plot3d color gardient legend

I am having a 3D plot in which the points are colored acording to some extra vector. My problem is to add a color gradient legend. This is my code:
x = matrix(NA,100,6)
#x value
x[,1] = runif(100, 0, 10)
#y value
x[,2] = runif(100, 0, 10)
#z value
x[,3] = x[,1]+x[,2]
#additional value
x[,4] = runif(100, 0, 1)
#find out in which interval each additional value is
intervals = seq(0,1,1/10)
x[,5] = findInterval(x[,4], intervals)
colours = topo.colors(length(intervals))
x[,6] = colours[x[,5]]
library(rgl)
plot3d(as.numeric(x[,1]),as.numeric(x.stab.in[,2]), as.numeric(x[,3]),
type="p", col=x[,6], size=2, xlab = "x(t)", ylab = "y(t)",
zlab = "z(t)")
decorate3d(xlab = "x", ylab = "y", zlab = "z")
legend3d("topright", legend = intervals, pch = 16, col = colours, cex=1, inset=c(0.02))
grid3d(c("x", "y+", "z"),col = "gray")
The plot looks like this
but I want the legend in a gradient form. That means I don't want separate points for each color but one box in which the colors fade into each other.
Here is a possible solution if you are okay with using scatterplot3d package instead of rgl. It is basically same but non-interactive. Here is your code modified to produce your expected result.
x = matrix(NA,100,6)
#x value
x[,1] = runif(100, 0, 10)
#y value
x[,2] = runif(100, 0, 10)
#z value
x[,3] = x[,1]+x[,2]
#additional value
x[,4] = runif(100, 0, 1)
#find out in which interval each additional value is
intervals = seq(0,1,1/10)
x[,5] = findInterval(x[,4], intervals)
#produce gradient of colors
#you can define different colors (two or more)
gradient <- colorRampPalette(colors = c("yellow", "green", "blue"))
colours <- gradient(length(intervals))
x[,6] = colours[x[,5]]
library(scatterplot3d)
png('3d.png', width = 600, height = 400)
layout(matrix(1:2, ncol=2), width = c(3, 1), height = c(1, 1))
scatterplot3d(as.numeric(x[,1]),as.numeric(x[,2]), as.numeric(x[,3]), type = 'p',
cex.symbols = 1.25, color=x[,6], pch = 16, xlab = "x(t)", ylab = "y(t)", zlab = "z(t)")
plot(x = rep(1, 100), y = seq_along(x[,6]),
pch = 15, cex = 2.5,
col = gradient(length(x[,6])),
ann = F, axes = F, xlim = c(1, 2))
axis(side = 2, at = seq(1, nrow(x), length.out = 11),
labels = 1:11,
line = 0.15)
dev.off()
This will plot the following graph
Here is another solution if you want to plot a gradient on an interactive 3d plot, such as if you needed to animate the plot into a movie.
require(car)
require(rgl)
require(RColorBrewer)
require(mgcv)
require(magick) #Only for creating the animation of the plot as a gif
#Creating mock dataset
Example_Data <- data.frame(Axis1 = rnorm(100),
Axis2 = rnorm(100),
Axis3 = rnorm(100))
Example_Data$Value <- Example_Data$Axis1+Example_Data$Axis2
#Defining function that takes a vector of numeric values and converts them to
#a spectrum of rgb colors to help color my scatter3d plot
get_colors <- function(values){
v <- (values - min(values))/diff(range(values))
x <- colorRamp(rev(brewer.pal(11, "Spectral")))(v)
rgb(x[,1], x[,2], x[,3], maxColorValue = 255)
}
#Writing function that takes a vector of numeric values and a title and creates
#a gradient legend based on those values and the title and suitable for addition
#to a scatter3d plot via a call to bgplot3d()
#Note, I didn't have time to make this automatically adjust text position/size for different size
#plot windows, so values may need to be adjusted manually depending on the size of the plot window.
gradient_legend_3d <- function(values, title){
min_val <- min(values)
max_val <- max(values)
x <- colorRamp(brewer.pal(11, "Spectral"))((0:20)/20)
colors <- rgb(x[,1], x[,2], x[,3], maxColorValue = 255)
legend_image <- as.raster(matrix(colors, ncol=1))
plot(c(0,1),c(0,1),type = 'n', axes = F,xlab = '', ylab = '', main = '') #Generates a blank plot
text(x=0.92, y = seq(0.5, 1,l=5), labels = signif(seq(min_val, max_val,l=5), 2), cex = 1.5) #Creates the numeric labels on the scale
text(x = 0.85, y = 1, labels = title, adj = 1, srt = 90, cex = 1.5) #Determines where the title is placed
rasterImage(legend_image, 0.87, 0.5, 0.9,1) #Values can be modified here to alter where and how wide/tall the gradient is drawn in the plotting area
}
#Creating scatter3d plot
scatter3d(x = Example_Data$Axis1, y = Example_Data$Axis2, z = Example_Data$Axis3, xlab = "Axis1", ylab = "Axis2", zlab = "Axis3", surface = F, grid = F, ellipsoid = F, fogtype = "none", point.col = get_colors(Example_Data$Value))
#Changing size of plotting window and orientation to optimize for addition of static legend
#This may not work on another machine, so the window may need to be adjusted manually
par3d(windowRect = c(0,23,1536,824))
par3d(userMatrix = matrix(c(-0.98181450, -0.02413967, 0.18830180, 0, -0.03652956, 0.99736959, -0.06260729, 0, -0.18629514, -0.06834736, -0.98011345, 0, 0, 0, 0, 1), nrow = 4, ncol = 4, byrow = T))
#Adding legend
bgplot3d(gradient_legend_3d(Example_Data$Value, "Point Value"))
#Animating plot and saving as gif
movie3d(spin3d(axis = c(0,1,0), rpm = 5), duration = 12, dir = getwd(), fps = 5, convert = FALSE, clean = FALSE)
frames <- NULL
for(j in 0:60){
if(j == 1){
frames <- image_read(sprintf("%s%03d.png", "movie", j))
} else {
frames <- c(frames, image_read(sprintf("%s%03d.png", "movie", j)))
}
}
animation <- image_animate(frames, fps = 10, optimize = TRUE)
image_write(animation, path = "Example.gif")
for(j in 0:60){
unlink(sprintf("%s%03d.png", "movie", j))
}
See link to view 3d plot generated by this code:
gif of 3d plot with gradient color scale

Maintain custom tick labels when using `c.trellis`

I have two trellis objects which I would like to combine using c.trellis from latticeExtra (the two figures can be downloaded here). As you can see below, the resulting plot inherits the tick labels from the first figure, whereas the labels from the second figure are discarded. Is it possible to keep different y-axis tick labels when using c.trellis?
library(latticeExtra)
rsq_plt <- readRDS("rsq.rds")
err_plt <- readRDS("err.rds")
latticeExtra:::c.trellis(rsq_plt, err_plt, layout = c(1, 2))
Just for the record, it seems like I finally came up with a proper solution thanks to the comprehensive customization options for trellis plots. Disabling scales in the upper plot (via scales = list(draw = FALSE); note that the file 'rsq.rds' has changed online) prior to performing c.trellis and subsequently update-ing the combined plot with customized y-axes solved the issue.
## combine plots and increase left padding
plt <- latticeExtra:::c.trellis(rsq_plt, err_plt, layout = c(1, 2))
plt <- update(plt,
scales = list(draw = FALSE),
par.settings = list(
layout.widths = list(left.padding = 6, right.padding = 0),
layout.heights = list(top.padding = 0, bottom.padding = 0)
))
## custom panel.axis
panel.fun <- function(...) {
# allow to draw labels outside panel
trellis.par.set("clip", list(panel = "off", strip = "off"))
# add upper y-axis
if (panel.number() == 1) {
panel.axis("left", at = 1, tck = .5, outside = TRUE,
labels = expression("r"^2))
panel.abline(v = 1, lty = 3, lwd = 1, col = "red")
panel.dotplot(lwd = .5, ...)
}
# add lower y-axis
if (panel.number() == 2) {
panel.axis("left", at = 2:4, outside = TRUE, tck = .5,
labels = c("MAE", "ME", "RMSE"))
panel.abline(v = 0, lty = 3, lwd = 1, col = "red")
panel.dotplot(..., lwd = 0.5)
}
}
## apply custom axes
update(plt, panel = panel.fun)

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()

How to change color in plot and the table of labels in plot?

plot(donnees.test$y,esvr1.pred,xlab = "Predicted Vlues", ylab = "Actual Values",type="p", yaxs="i",ylim=c(2,18),xaxs="i",xlim=c(2,18))
points(donnees.test$y,esvr1.pred, col=1,pch =19)
points(donnees.test$y,esvr1.pred, col=2,pch =20)
points(donnees.test$y,ANFIS, col=6,pch =3)
points(donnees.test$y,NN, col=4,pch =4)
#points(donnees.test$y,esvr1.pred, col=3)
abline(a = 0, b = 1, col = 3)
abline(a = 0, b = 1.25, col = 2)
text(9,14, "+25% Line", col = 2, adj = c(-.1, -.1))
abline(a = 0, b = 0.75, col = 2)
text(14.2,10, "-25% Line", col = 2, adj = c(-.1, -.1))
leg.txt <- c("SVR_rbf", "SVR_poly","ANFIS","NN")
legend(list(x = 2,y = 17.95), legend = leg.txt, col = 1:6, pch = c(19,20,3,4))
I changed the color of ANFIS that i want but in the table of labels the color of ANFIS did not changed. how should i changed it?
And if i wanna to add some text above of the plot in the plot tab what code i should add to my source?
To add a title to your plot, use the argument
main="the title here"
inside your plot command, or if you're adding it afterwards, use
title("the title here").
Your problem with the colours in your legend is that you have four items in your legend:
("SVR_rbf", "SVR_poly","ANFIS","NN"),
but you are giving the plot command six colours:
col = 1:6.
Try doing
col=1:4
instead.

Resources