Adding names on map using tmap/tmaptools [duplicate] - r

I'm trying to add some text labels a tmap plot.
library(tmap)
library(raster)
jnk <- getData("GADM",country="IND",level=2)
map_file <- tm_shape(jnk) +
tm_polygons() +
tm_text("NAME_1", remove.overlap = TRUE)
My problem is I'm getting duplicate text when I plot (can't post image since I'm new). I think I might have to group by some sort of geometry and NAME_1 combination but I'm unsure where to go from here.
Any advice would be great!

I am not certain what is your problem (as you were unable to post your image) but consider this code:
library(tmap)
library(raster)
jnk <- getData("GADM",country="IND",level=1)
tm_shape(jnk) + tm_polygons("NAME_1", legend.show = F) +
tm_text("NAME_1", size = 1/2)
I have made some minor changes to your code:
downloaded level 1 detail instead of level 2 detail (districts were too numerous, states are OK)
removed legend from the tm_polygons() call
made the letters of tm_text() smaller (to fit the north-eastern states)

Related

how to show raster cell values with tmap?

The code below plots raster cell values. How can I do the same with package tmap?
library(terra)
pai_sim <- rast(ncols=6, nrows=6,
xmin=1, xmax=60,
ymin=1, ymax=60,
res=10)
values(pai_sim) <- 1
plot(pai_sim)
text(pai_sim)
The code below results in errors (incorrect number of dimensions and can´t find object). I have searched using different terms e.g. tmap tm_raster show cell values, but have not found a solution. This is a teaching example so I want to avoid additional steps e.g to not convert to polygon on the fly if at all possible.
library(tmap)
tm_shape(pai_sim) +
tm_raster() +
tm_text("lyr.1")
tm_shape(pai_sim) +
tm_raster() +
tm_text(lyr.1)

Is there a way to create a kissing people curve using ggplot2 in R

Is it possible to create custom graphs using ggplot2, for example I want to create a graph of kissing people.
Simple variant
Not completely, but partially, I was able to reproduce it, everything except for the "lines of the eyes" is not clear how to mark them
But how to make a more complex graph of kissing people. In general, is it possible to somehow approximate such a curve, more voluminou?
thank you for your help.
perhaps not what you are looking for, but if you have already got the image, and want to reproduce it in ggplot, then you can use the following method:
library(tidyverse)
library(magick)
library(terra)
# read image
im <- image_read("./data/kiss_1.png")
# conver to black/white image
im2 <- im %>%
image_quantize(
max = 2,
colorspace = "gray" )
# get a matrix of the pixel-colors
m <- as.raster(im2) %>% as.matrix()
# extract coordinates of the black pixels
df <- as.data.frame(which(m == "#000000ff", arr.ind=TRUE))
df$row <- df$row * -1
# plot point
ggplot(df, aes(x = col, y = row)) + geom_point()

Fixing spacing issue with annotations in cowplot/patchwork

I'm trying to combine several figures drawn in PowerPoint into a panel, using patchwork, cowplot, magick. However, I always feel that the distance between the annotation and the actual figure is too big, and I'm struggling to find a way that minimises the distance.
Is there a way to fix this issue?
Here's is my code.
library(patchwork)
library(cowplot)
library(magick)
# You can test with any other image, so the code should be reproduceable
design <- "./design.png"
courses <- "./courses.png"
# here I draw the figure using draw_image
design <- ggdraw() + draw_image(design, x = 0,
y = 0)
courses <- ggdraw() + draw_image(courses)
design / courses + plot_annotation(tag_levels = 'A')
A solution that fixed the problem was to use ggsave and playing around with the width and height, as suggested in the comments. For me, this one worked.
plot <- design / courses + plot_annotation(tag_levels = 'A')
ggsave("myplot.tiff", device = "tiff", height = "0.5")

Trying to plot in tmap shapefile with attribute

I am trying to work with municipality data in Norway, and I'm totally new to QGIS, shapefiles and plotting this in R. I download the municipalities from here:
Administrative enheter kommuner / Administrative units municipalities
Reproducible files are here:
Joanna's github
I have downloaded QGIS, so I can open the GEOJson file there and convert it to a shapefile. I am able to do this, and read the data into R:
library(sf)
test=st_read("C:/municipality_shape.shp")
head(test)
I have on my own given the different municipalities different values/ranks that I call faktor, and I have stored this classification in a dataframe that I call df_new. I wish to merge this "classification" on to my "test" object above, and wish to plot the map with the classification attribute onto the map:
test33=merge(test, df_new[,c("Kommunekode_str","faktor")],
by=c("Kommunekode_str"), all.x=TRUE)
This works, but when I am to plot this with tmap,
library(tmap)
tmap_mode("view")
tm_shape(test33) +
tm_fill(col="faktor", alpha=0.6, n=20, palette=c("wheat3","red3")) +
tm_borders(col="#000000", lwd=0.2)
it throws this error:
Error in object[-omit, , drop = FALSE] : incorrect number of
dimensions
If I just use base plot,
plot(test33)
I get the picture:
You see I get three plots. Does this has something to do with my error above?
I think the main issue here is that the shapes you are trying to plot are too complex so tmap is struggling to load all of this data. ggplot also fails to load the polygons.
You probably don't need so much accuracy in your polygons if you are making a choropleth map so I would suggest first simplifying your polygons. In my experience the best way to do this is using the package rmapshaper:
# keep = 0.02 will keep just 2% of the points in your polygons.
test_33_simple <- rmapshaper::ms_simplify(test33, keep = 0.02)
I can now use your code to produce the following:
tmap_mode("view")
tm_shape(test_33_simple) +
tm_fill(col="faktor", alpha=0.6, n=20, palette=c("wheat3","red3")) +
tm_borders(col="#000000", lwd=0.2)
This produces an interactive map and the colour scheme is not ideal to tell differences between municipalities.
static version
Since you say in the comments that you are not sure if you want an interactive map or a static one, I will give an example with a static map and some example colour schemes.
The below uses the classInt package to set up breaks for your map. A popular break scheme is 'fisher' which uses the fisher-jenks algorithm. Make sure you research the various different options to pick one that suits your scenario:
library(ggplot2)
library(dplyr)
library(sf)
library(classInt)
breaks <- classIntervals(test_33_simple$faktor, n = 6, style = 'fisher')
#label breaks
lab_vec <- vector(length = length(breaks$brks)-1)
rounded_breaks <- round(breaks$brks,2)
lab_vec[1] <- paste0('[', rounded_breaks[1],' - ', rounded_breaks[2],']')
for(i in 2:(length(breaks$brks) - 1)){
lab_vec[i] <- paste0('(',rounded_breaks[i], ' - ', rounded_breaks[i+1], ']')
}
test_33_simple <- test_33_simple %>%
mutate(faktor_class = factor(cut(faktor, breaks$brks, include.lowest = T), labels = lab_vec))
# map
ggplot(test_33_simple) +
geom_sf(aes(fill = faktor_class), size= 0.2) +
scale_fill_viridis_d() +
theme_minimal()

trouble using RColorBrewer with spplot

I feel like many similar questions have been asked but I haven't found a solution to my problem yet in the related questions.
I am trying to change the colors on my map using spplot and the col.region command.
I have tried setting up a palette with the RColorBrewer package. I have tried using various values for the n: 5,6,7 (I am using 5 quantiles for my cuts) and even 1 to see if it would result in any observable change, but to no avail. I have also changed the choice of color several times but it also didn't bring any change.
I have also tried setting up a color function the colorRampPalette function but also unsuccessfully.
The data I'm using can be downloaded here (sorry, I couldn't figure out how to upload it with the question) : http://www.data.drees.sante.gouv.fr/ReportFolders/reportFolders.aspx, by typing "APL" in search bar and taking the first excel file (2015); apologies can't manage to link it properly either)
My code is the following:
library(maptools)
library(raster)
library(RColorBrewer)
library(readxl)
library(classInt)
apl15 <- read_excel("DATA USED")
france_com<- getData(name = "GADM",
country="FRA",
level=5)
paca <- subset(fr_com,NAME_1=="Provence-Alpes-Côte d'Azur")
apl15 <- data.frame(apl15)
names(apl15) <- c("code_com","name_com","apl","apl_young","pop_com","dept","apl*pop")
id_paca <- match(paca$NAME_5,apl15$name_com)
key_paca<- apl15[id_paca,"apl"]
paca$apl <- key_paca
apl.qt <- classIntervals(paca$apl,
n=5,
style="quantile")
br <- apl.qt$brks
offs <- 0.0000001
br[1] <- br[1] - offs
br[length(br)] <- br[length(br)] + offs
paca$apl_q <- cut(paca$apl,br)
display.brewer.all(type="seq")
my.palette <- brewer.pal(6, "OrRd")
spplot(paca,"apl_q",
col.region=my.palette,
main="APL en PACA", cex.=.7)
I expect this map but with colors corresponding to the palette I have selected.
my data mapped onto a region:
.
Thanks in advance for any help!

Resources