I am trying to make a plot of a map from raster data. I am using this code:
library(raster)
library(rgdal)
library(classInt)
library(RColorBrewer)
NDII = raster("G:\\Sheyenne\\image_differencing\\NDII\\differenced.tif")
value.vector = values(NDII)
breaks.qt = classIntervals(value.vector, n = 6, style = "jenks", intervalClosure = "right")
print (plot(NDII, breaks=breaks.qt$brks, col = brewer.pal(6, "Set1")))
but this returns:
Error in print(plot(NDII, breaks = breaks.qt$brks, col = brewer.pal(6, :
error in evaluating the argument 'x' in selecting a method for function 'print': Error in .asRaster(x, col, breaks, zrange, colNA, alpha = alpha) :
could not find function "brewer.pal"
You provide no reproducible example, and I can't reproduce your error.
The following code, which is the same as yours using the reproducible example of the R logo as a raster (and with the shortcut of using NDII[] instead of storing values(NDII) in a variable) works just fine for me...
library(raster)
library(rgdal)
library(classInt)
library(RColorBrewer)
NDII = raster(system.file("external/rlogo.grd", package="raster"))
# next line is really slow, I'd advise to run crop(NDII, extent(0,20,0,20))
# before to make quick tests
breaks.qt = classIntervals(NDII[], n = 6, style = "jenks",
intervalClosure = "right")
plot(NDII, breaks=breaks.qt$brks, col = brewer.pal(6, "Set1"))
Do you reproduce your error with this code? Maybe you can start with a new, fresh session?
Related
I have been trying to plot a raster layer by setting the value 1 to the color white. I looked at many examples but still couldn't construct the colors as I wish. I want contrasting colors for the values below and above 1. I would like them start with a light tone and get darker as they go further from 1. I also posted the figure that I managed to create so far. It looks a bit weird since it is based on made up data. I can't share the real data unfortunately. The best would be to create this using viridis colors, but I don't know how doable it is.
I wonder if anyone has any suggestions?
I got the idea of breakpoints and colors from the following post :https://gis.stackexchange.com/questions/17339/raster-legend-in-r-how-to-colour-specific-values .
I got the shapefile from here : https://gadm.org/download_country.html .
Here is my example:
library(rgdal)
library(raster)
library(sp)
library(sf)
set.seed(123)
proj = "+units=km +proj=utm +zone=37 +ellps=clrk80 +towgs84=-160,-6,-302,0,0,0,0 +no_defs"
map0 = readOGR(dsn = "dataFiles/gadm40_NGA_shp", #https://gadm.org/download_country.html (Nigeria/shapefile)
layer = "gadm40_NGA_0")
map0_trnsfrmd = spTransform(map0,proj)
predRaster <- raster(ncol=400, nrow=400, xmn=-3805.7869, xmx=-2222.120, ymn=562.5405, ymx=1828.165)
res(predRaster) = 5
projection(predRaster) = "+units=km +proj=utm +zone=37 +ellps=clrk80 +towgs84=-160,-6,-302,0,0,0,0 +no_defs"
idx = 1:80201 # index for the cell numbers
val = c(rnorm(50000), rep(1,10201),runif(20000,min=0, max=3))
r = setValues(predRaster, values = val, index=idx) # assign values to the cells
r = raster::mask(crop(r, extent(map0_trnsfrmd)), map0_trnsfrmd, snap = 'out')
below=val[val<1]
above=val[val>1]
min(below)
[1] -4.289319
max(above)
[1] 4.438207
max(below)
[1] 0.9998253
min(above)
[1] 1.000105
breakpoints = c(-4.289319, 0.9998253, 1.000105, 4.438207)
colors = c("red","white","blue")
par(mgp=c(4,1,0), mar=c(5,7,3,1)+0.1)
plot(r,las=1, asp = 1, xlab="Easting", ylab="Northing", axis.args = list(cex.axis=1),
legend.shrink =1,legend.width=2, cex.lab=2, cex.axis=1.5, legend.args = list("title", cex =1),breaks=breakpoints,col=colors)
exampleplot
Please look below on the colors definition. I have removed the shape for clarity.
library(rgdal)
library(raster)
library(sp)
library(sf)
set.seed(123)
predRaster <- raster(ncol=400, nrow=400, xmn=-3805.7869, xmx=-2222.120, ymn=562.5405, ymx=1828.165)
res(predRaster) = 5
projection(predRaster) = "+units=km +proj=utm +zone=37 +ellps=clrk80 +towgs84=-160,-6,-302,0,0,0,0 +no_defs"
idx = 1:80201 # index for the cell numbers
val = c(rnorm(50000), rep(1,10201),runif(20000,min=0, max=3))
r = setValues(predRaster, values = val, index=idx) # assign values to the cells
below=val[val<1]
above=val[val>1]
colors = c(colorRampPalette(c(rgb(1,0,0,1), rgb(1,0,0,0.1)), alpha = TRUE)(19),"white", colorRampPalette(c(rgb(0,0,1,0.1), rgb(0,0,1,1)), alpha = TRUE)(19))
plot(r, col=colors, xlab="Easting", ylab="Northing", axis.args = list(cex.axis=1),
legend.shrink =1,legend.width=2, cex.axis=1.5, legend.args = list("title", cex =1))
You can increase the number of colors on both sides. Please check the help for colorRampPalette() function.
Created on 2022-08-31 by the reprex package (v2.0.1)
I have 11 plots and used a looping function to plot them see my code below. However, I can't get them to fit in just 1 page or less. The plots are actually too big. I am using R software and writing my work in RMarkdown. I have spent almost an entire week trying to resolve this.
group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i <- graph3$plots[[i]] +
labs(title = Firm_category[i]) +
stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
#output3.long data sample below as comments
#Firm_category billmonth Means.type means
#Agric 1 Before 38.4444
#Agric 1 After 51.9
Complete data is on my github: https://github.com/Fridahnyakundi/Descriptives-in-R/blob/master/Output3.csv
This code prints all the graphs but in like 4 pages. I want to group them into a grid. I have tried to add all these codes below just before my last curly bracket and none is working, please help me out.
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
library(ggpubr)
print(ggarrange(graph3.i[1:11], nrow = 4, ncol = 3))
I tried the gridExtra command as well (they all seem to do the same thing). I am the one with a mistake and I guess it has to do with my list. I read a lot of similar work here, some suggested
dev.new()
dev.off()
I still didn't get what they do. But adding either of them caused my code to stop.
I tried defining my 'for' loop function say call it 'XX', then later call it to make a list of graph but it returned NULL output.
I have tried defining an empty list (as I read in some answers here) then counting them to make a list that can be printed but I got so many errors.
I have done this for almost 3 days and will appreciate your help in resolving this.
Thanks!
I tried to complete your code ... and this works (but I don't have your 'stat.test' object). Basically, I added a graph3.i <- list() and replaced graph3.i in the loop ..
Is it what you wanted to do ?
library(magrittr)
library(dplyr)
library(rstatix)
library(ggplot2)
library(ggpubr)
data <- read.csv(url('http://raw.githubusercontent.com/Fridahnyakundi/Descriptives-in-R/master/Output3.csv'))
graph3 <- data %>% group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
graph3.i <- list()
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i[[i]] <- graph3$plots[[i]] +
labs(title = Firm_category[i]) # +
# stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
I was using Seurat to analyse single cell RNA-seq data and I managed to draw a heatmap plot with DoHeatmap() after clustering and marker selection, but got a bunch of random characters appearing in the legend. They are random characters as they will change every time you run the code. I was worrying over it's something related to my own dataset, so I then tried the test Seurat object 'ifnb' but still got the same issue (see the red oval in the example plot).
example plot
I also tried importing the Seurat object in R in the terminal (via readRDS) and ran the plotting function, but got the same issue there, so it's not a Rstudio thing.
Here are the codes I ran:
'''
library(Seurat)
library(SeuratData)
library(patchwork)
InstallData("ifnb")
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
x <- NormalizeData(x)
x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})
features <- SelectIntegrationFeatures(object.list = ifnb.list)
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features)
immune.combined <- IntegrateData(anchorset = immune.anchors)
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
DefaultAssay(immune.combined) <- 'RNA'
immune_markers <- FindAllMarkers(immune.combined, latent.vars = "stim", test.use = "MAST", assay = 'RNA')
immune_markers %>%
group_by(cluster) %>%
top_n(n = 10, wt = avg_log2FC) -> top10_immune
DoHeatmap(immune.combined, slot = 'data',features = top10_immune$gene, group.by = 'stim', assay = 'RNA')
'''
Does anyone have any idea how to solve this issue other than reinstalling everything?
I have been having the same issue myself and while I have solved it by not needing the legend, I think you could use this approach and use a similar solution:
DoHeatmap(immune.combined, slot = 'data',features = top10_immune$gene, group.by = 'stim', assay = 'RNA') +
scale_color_manual(
values = my_colors,
limits = c('CTRL', 'STIM'))
Let me know if this works! It doesn't solve the source of the odd text values but it does the job! If you haven't already, I would recommend creating a forum question on the Seurat forums to see where these characters are coming from!
When I use seurat4.0, I met the same problem.
While I loaded 4.1, it disappeared
This is final output I got, I'm supposed to get the final output as a single file with two bands:
Following is the code which I am using:
A11 <-brick("E:/Official/PROJECTS/R_Progrm/1.tif") // to read multiband image
B11<-brick("E:/Official/PROJECTS/R_Progrm/3.tif") // To read multiband image
mos1 <- mosaic(A11,B11,fun=max,tolerance=0.5,
filename="Mosaic_new",overwrite=TRUE)
plot(mos1,main="Mosaic_new1")
writeRaster(x=mos1,file="E:/Official/PROJECTS/R_Progrm/M11.tif",options="INTERLEAVE=BAND",format="GTiff",datatype="FLT8S",overwrite=TRUE)
The plot that you have shown in your question, is showing both the bands of your output image. So, there should not be any problem with your code and its output. If the problem is related to visualizing all the bands as an RGB Image, then you have to modify the parameters of plot function that means you have to provide the band combination. For example:
plotRGB(a, r = 4, g = 3, b = 2, axes=TRUE, main="3 Band Color Composite Image")
box(col="white")
Also, you can try the code given below which is working fine for me, and I hope it will resolve your problem.
a <- stack("Path to first raster")
b <- stack("Path to second raster")
rast.list <- list(a,b)
rast.list$fun <- mean
rast.mosaic <- do.call(mosaic,rast.list)
plot(rast.mosaic)
writeRaster(rast.mosaic,"Output_Raster_Name",format="GTiff",overwrite=TRUE)
rm(list = ls())
gc()
memory.limit(size= 2000)
library(rgdal)
library(raster)
install.packages("gdalUtils")
library(gdalUtils)
library(sp)
setwd("E:/Official/PROJECTS/R_Progrm/MOs/")
list.files()
file1=file.path(getwd(), "", "1.tif")
gdal_setInstallation()
valid_install <- !is.null(getOption("gdalUtils_gdalPath"))
if(require(raster) && require(rgdal) && valid_install)
{
layer1 <- file.path(getwd(), "", "1.tif")
layer2 <- file.path(getwd(), "", "3.tif")
file_list=c(layer1,layer2)
mosaic_rasters(gdalfile=file_list,dst_dataset="E:/Official/PROJECTS/R_Progrm/MOs//test_mosaic.GTiff",separate=TRUE,of="GTiff",verbose=TRUE)
gdalinfo("test_mosaic.GTiff")
}
I am using biwavelet package to conduct wavelet coherence analysis. When I want to set my own x ticklabel, I find axisis not working. The following gives a reproducible example. Thanks.
require(biwavelet)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.cb = TRUE, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,10,1))
The thing that was breaking your plot was plot.cb = TRUE.
In the source code for plot.biwavelet the author notes the following about the plot.cb option:
## Add color bar: this must happen after everything, otherwise chaos
ensues!
So that was the problem -- you invoked axis() after plot.cb and chaos ensued. However, you can manually add back the color bar using image.plot from the fields package, after having run plot without plot.cb then having added your axis().
pacman::p_load(biwavelet,fields)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,20,2))
image.plot( zlim=c(0,25), legend.only=TRUE)
You can customize the ticks and the color bar to your liking this way!