I want to adjust the graph area in ggplot2 - r

I made the following graph using the geomnet package and ggplot2. Then exported it to a pdf. But the graph by itself seems to be larger than the graphing area. it seems to be framed in a small square, as you can see in this picture:
graph
I don't know how to change the size of the square that's framing my graph so that the net nodes will be shown fully in my pdf. Thanks in advance.
Here's the code i'm using, and a data example:
red_list<-data_frame(From=c("A","B","C","D","D"),To=c("C","C","D","Z","A"))
red_list%>%ggplot(aes(from_id=From,to_id=To))+
geom_net(layout.alg = "circle", labelon = TRUE,
size = 12, directed = TRUE, fontsize=2, vjust = 0.5, labelcolour = "grey80",
arrowsize = 1.5, linewidth = 0.5, arrowgap = 0.05, col="darkred",
selfloops = F, ecolour = "grey40") +
theme_net() +
theme(plot.title=element_text(hjust=.5),
plot.subtitle=element_text(hjust=.5))+
ggtitle(label=paste("Figura",i,sep=" "),subtitle = paste("Interacciones entre los sectores de",names(red_list)[i],by=" ")))

I'm not sure how well it will work with graphs, but I uselly play with coord_cartesian(xlim = c(...,...), ylim = c(...,...) to adjust the plotting area.

Related

How to export an annotated plot made with ggarrange using cairo so that the plot boundary lines are removed?

I want to make a graphic made with ggarrange, use shared labels for the axis and export it with cairo to have a nice image.
The problem is that when I add it to latex the graphic is surrounded by a line which crosses the axis labels. How can I remove that line from the graphic?
6 plots (m1_g to m6_g) are combined with ggarrange to make a graphic called figure, then its annotated with annotate_figure to produce the graphic called figure2.
figure = ggarrange(m2_g+rremove("ylab")+rremove("xlab"),m1_g + rremove("ylab")+rremove("xlab"),m3_g +rremove("xlab")+ rremove("ylab"),m4_g +rremove("xlab") + rremove("ylab"),
m5_g +rremove("xlab")+ rremove("ylab"),m6_g +rremove("xlab")+ rremove("ylab"),
common.legend = TRUE, legend="right",ncol = 6)
figure2 = annotate_figure(figure, left = textGrob("Voltaje [mV]", rot = 90, vjust = 1, gp = gpar(cex = 1.3)),bottom = textGrob("Tiempo E-1 [s]", gp = gpar(cex = 1.3)))
ggsave("measurements_P4.png",plot = figure2, width = 10,type = "cairo")
`
This is the problem i am facing

Fix axis numbering in Circlize chord diagram and font issues

I have been experimenting with the 'circlize' package but I have been having issues with my axis label spacing. I wanted to customize the axis labelling to have major ticks at a specified intervals. I succeeded using the below code, but my issues are that as I change font size, the outer labels of each sector of the chord diagram, move in (a white space issue I believe). I cant find anything through my searching and need some help to fix this issue. The larger the font size, the more drastic the labels move inwards.
Additionally, I cannot find out how to change the font to 'Calibri' or bold (I have tried extrafonts and showtext but may not be implementing it correctly). Any thoughts would be appreciated.
Here is a reproducible example:
#sample matrix
A<-c(4680,0,0,0,0,0,0,0,0,0)
B<-c(109,23323,0,0,0,0,0,0,0,0)
C<-c(9,12,5405,0,0,0,0,0,0,0)
D<-c(19,25,26,4615,0,0,0,0,0,0)
E<-c(108,816,32,38,5511,0,0,0,0,0)
F_1<-c(50,319,67,55,202,18198,0,0,0,0)
G<-c(15,11,8,178,11,18,38279,0,0,0)
H<-c(24,180,22,39,171,212,14,10673,0,0)
I<-c(211,2378,18,28,1603,251,25,188,34458,0)
J<-c(162,1623,31,48,1003,370,34,265,5319,27235)
m <- rbind(A,B,C,D,E,F_1,G,H,I,J)
row.names(m) <- LETTERS[seq(1,10,1)]
colnames(m)<- LETTERS[seq(1,10,1)]
The graph:
colfunc <- colorRampPalette(c("#856705", "#d3d3d3", "#113069"))
grid.col <- setNames(colfunc(10), LETTERS[seq(1,10,1)])
grid.col
library(showtext); library(circlize)
#my attempt to load the correct font but I am unsure how to call the font within circlize.
font_add(family = "Calibri", regular = "C:/Windows/Fonts/calibri.ttf", italic ="C:/Windows/Fonts/calibrii.ttf", bold = "C:/Windows/Fonts/calibrib.ttf", bolditalic = "C:/Windows/Fonts/calibriz.ttf")
circos.clear()
showtext_auto()
circos.par(start.degree = 90, gap.degree = 5)
par(family = "Calibri") #tried to set the family to "Calibri"
chordDiagram(m/1000,
transparency = 0.5,
grid.col = grid.col,
annotationTrack = "grid",
self.link = 1,
link.lwd = 0.5, # Line width
link.lty = 1,
link.border = "light grey",
annotationTrackHeight = mm_h(10))
for(si in get.all.sector.index()) {
circos.axis(h = 'top',
major.at = c(0,5,10,15,20,25,30,35,40,45,50),
labels = c(0,5,10,15,20,25,30,35,40,45,50),
minor.ticks = 4,
labels.cex = fontsize(30),
sector.index = si,
track.index = 1,
labels.niceFacing = TRUE)
xlim = get.cell.meta.data("xlim", sector.index = si, track.index = 1)
ylim = get.cell.meta.data("ylim", sector.index = si, track.index = 1)
circos.text(mean(xlim),
mean(ylim),
si,
sector.index = si,
track.index = 1,
niceFacing = TRUE,
cex = fontsize(50),
col = "white",
font = par("Calibri"))
}
dev.copy(png, "test chord diagram.png", width = 5, height = 5, units = "cm", res = 600)
dev.off()
circos.clear()
With this, I get this graph:
As you can see from the graph, the '0' are all off position of their respective mark. Additionally , sector 'C' and 'D' have their axis labels moved in and are overlapping (including for sector 'J').
So, if anyone has an idea to move the end labels above their respective position, how to change the font to 'Calibri' and to bold, that would be great.
Thank you.
Well it seemed that the labels were fixed by using "labels.pos.adjust = c(0,0)", in the "circos.axis" argument. The only issue left is that the font still needs to be change to calibri.

Increase space between axis titles and axis using tmap in R

I'm having an issue with finding answers for a fairly simple question. I just need to move the axis titles (xlab and ylab) away from the axes. I haven't uploaded reproducible data since the files are large shapefiles, but I can upload it if needed (I figure it's a fairly straightforward answer). I have attached the code I've used so far as well as the map I'm struggling with:
LandUseMap <- tm_shape(LandUseshape, ylim = c(50.45, 50.68), xlim=c(-105,
-104.7), projection = "longlat") +
tm_fill("COVTYPE", title = "Land Cover Type",style="fixed",breaks=c(20,30,34,50,110,121,122,220,230),
labels=c("Water","Non-Vegetated Land","Developed","Shrubland","Grassland","Annual Cropland","Perennial Crops/Pasture","Broadleaf","No Data"),
palette=manualpal) +
tm_borders("grey") +
tm_legend(outside = TRUE, text.size = .65) +
tm_layout(frame = FALSE,asp =NA, outer.margins = c(0.05,0.1,0,0), inner.margins = c(0.05,0.05,0.01,0.05))+
tm_grid(y=c(50.45, 50.50, 50.55, 50.60, 50.65), x=c(-105.0,-104.9,-104.8,-104.7),labels.inside.frame = FALSE, col = "#00ff0000",
labels.size =0.8)+
tm_xlab("Longitude", size = 1)+
tm_ylab("Latitude", size = 1)+
tm_scale_bar(size = 1, position = c(0,0.8)) +
tm_compass(size=2.5,north = 0,position = c(0,0.9))
LandUseMap
Here's the map:

R: tmap Legend Formatting

I am trying to create a function to map different variables for a specific state's school districts. However I a running into some problems formatting the legend. At the moment I have it laid out the best way to fit the maps(horizontally), but some of the text is being cut off (Below Average Poverty Rate), and I'd like to add % to the number labels in the legend. My code and an image of the legend is below. Any help you can provide would be very much appreciated. Thank You.
MakeLEAMap <-function(StateNum,NCHE_VAR,VAR1_NAME,In,Folder){
as.character(substitute(StateNum))
as.character(substitute(NCHE_VAR))
as.character(substitute(NCHE_In))
as.character(substitute(VAR1_NAME))
as.character(substitute(Folder))
map <-
tm_shape(LEA_1415_New[LEA_1415_New#data$STATEFP == StateNum, ]) +
tm_polygons(NCHE_VAR,border.col="#000000", lwd= .5, textNA="Below Average \nPoverty Rate" , palette = 'Blues', style="quantile",
title=paste(In," State LEA Map: ",VAR1_NAME),
legend.is.portrait = FALSE) +
tm_text("LCITY", size=NCHE_VAR,scale=.8, root=2,print.tiny = FALSE, size.lowerbound = .85, bg.alpha = .75,
remove.overlap = TRUE,legend.size.show = FALSE, col="black") +
tm_layout( legend.title.size = 3,
frame = FALSE, inner.margins = c(0,.0,.05,.0), asp = 1.5,
legend.text.size = 1,
legend.outside=TRUE, legend.outside.position = 'bottom',
legend.frame = TRUE,
legend.outside.size = .3, legend.position = c(-0.1, 0.3))
save_tmap(map, filename=paste("State_Maps_TEST/",Folder,"/",In,".pdf", sep = ''),width=8, height=8 )
}
MakeLEAMap("48","Abv_Diff_Home_Pov","% Children in Poverty minus \n% Children HCY (Ages5-17)",
"TX","ALL")
Here is what the legend looks like now
To make the legend show percentages use this function inside your tm_polygons call:
legend.format=list(fun=function(x) paste0(formatC(x, digits=0, format="f"), " %"))
You can play with the digits (decimal points) and you can drop the space before % sign if you desire.
To make the legend more legible increase the space around your map by making a bigger bbox (possibly using extent function from raster package to read bbox of your spatial object and then enlarging it) and move the legend by adjusting its position.
This is what I came up with in a different context, but one which also called for a percentage sign in tmap legend.

Producing an inset map with the tmap package in R

I am trying to produce an inset map of London alongside a larger map of the UK. I'm using the package "tmap" which I have found to be an excellent package and particularly easy to move to having used ggplot2 for a while. However, the documentation on how to produce an inset map using tmap is a bit unclear. The reference manual describes how it should be possible to produce an inset map using:
save_tm(...insets_tm = NULL, insets_vp = NULL)
but it is not clear how the second command, insets_vp, should be used. I have only found one example which actually provides suggested syntax for producing an insetmap using tmap:
alaska <- tm_shape(shp_alaska) + … print(alaska, vp=viewport(x=.1,
y=.15, width=.2, height=.3))
See here for the source of the above code. This doesn't actually show how the map of the USA and Alaska/Hawaii are combined. As for my own attempts at coding, I have tried the following (dplyr, magrittr, rgdal, GISTools, RColorBrewer, tmap are all loaded, R vn 3.3.2, RStudio 1.0.136):
I first create two tmap objects polygon and points for all of the UK (UK_Im_Sec) and London (London_Im_Sec):
UK_Im_Sec<-tm_shape(UKNI_LA_ll, is.master = TRUE)+
tm_borders(lwd=0.25)+
tm_shape(Immobile_residuals)+
tm_dots(col="Sec_Name", style="cat", palette="Set1", title="Socio-economic background (NS-SEC)")+
tm_layout(title="Mapping outlier residuals - non-predicted 'immobility' (Social class)", title.size = 3.0,
title.position=c("center","TOP"),legend.outside = TRUE,
legend.outside.position = "right",frame = FALSE)
LDN_Im_Sec<-tm_shape(Immobile_resids_LDN)+
tm_dots(col="Sec_Name", style="cat", palette="Set1", size = 0.25,title="Socio-economic background (NS-SEC)")+
tm_shape(LDN_Poly, is.master = TRUE)+
tm_borders(lwd=0.25)+
tm_text(text="NAME", size = 0.6, auto.placement=TRUE)+
tm_layout("London",title.position = c("center", "BOTTOM"),legend.outside = TRUE, legend.outside.position = "right", frame = FALSE)
I then try to save out a pdf which combines both objects:
save_tmap(UK_Im_Sec,insets_tm = LDN_Im_Sec,filename="ZRMdlNoRg_SEC_-3to-5SDs_ImmobResids_FINAL.pdf", dpi=600)
This prints the pdf but only with the map of the UK. So,
I try and add insets_vp into the code:
save_tmap(UK_Im_Sec,insets_tm = LDN_Im_Sec,insets_vp=UK_Im_Sec, filename="ZRMdlNoRg_SEC_-3to-5SDs_ImmobResids_FINAL.pdf", dpi=600)
But this gives the following error code:
Error in save_tmap(UK_Im_Sec, insets_tm = LDN_Im_Sec, insets_vp = UK_Im_Sec, :
Insets and/or its viewports not in the correct format
I then try to combine the suggested syntax for print(x, viewport=(x=,y=,h=,w=) with insets_vp, as follows:
save_tmap(UK_Im_Sec,insets_tm = LDN_Im_Sec,insets_vp=viewport(x=2, y=.15, width=.2, height=.3), filename="ZRMdlNoRg_SEC_-3to-5SDs_ImmobResids_FINAL.pdf", dpi=600)
Error in inherits(insets_vp, "viewport") :
could not find function "viewport"
I know that other people have had difficulty producing inset maps in other packages and that there are questions that have already been asked and resolved for other packages, notably in ggplot (I can't link to the questions because of limits on links), but as far as I know there is nothing on this particular tmap issue.
This is my first question here so apologies for any errors in laying out the question.
You'll need to load the grid package. So, this should work
library(grid)
save_tmap(UK_Im_Sec,insets_tm = LDN_Im_Sec,insets_vp=viewport(x=2, y=.15, width=.2, height=.3), filename="ZRMdlNoRg_SEC_-3to-5SDs_ImmobResids_FINAL.pdf", dpi=600)
I'll update the US choropleth demo soon, with a save_tmap example.
The last chart in the tmap demo documentation has insets of Alaska and Hawaii. Below is the code, I've just removed the fill variable:
library("readxl")
library("maptools")
library("grid")
library("tmap")
library("tmaptools")
# function to obtain US county shape
get_US_county_2010_shape <- function() {
dir <- tempdir()
download.file("http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip", destfile = file.path(dir, "gz_2010_us_050_00_20m.zip"))
unzip(file.path(dir, "gz_2010_us_050_00_20m.zip"), exdir = dir)
read_shape(file.path(dir, "gz_2010_us_050_00_20m.shp"))
}
# obtain US county shape
US <- get_US_county_2010_shape()
# split shape
US_cont <- US[!(US$STATE %in% c("02","15","72")),]
US_AK <- US[US$STATE == "02", ]
US_HI <- US[US$STATE == "15",]
# create state boundaries
US_states <- unionSpatialPolygons(US_cont, IDs=US_cont$STATE)
After setting up the shapefiles, here is where the viewport windows are added to the plot:
# change back to the plotting mode
tmap_mode("plot")
# plot contiguous US
tm_shape(US_cont, projection=2163) +
tm_polygons(border.col = "grey50", border.alpha = .5, title = "", showNA = TRUE) +
tm_shape(US_states) +
tm_borders(lwd=1, col = "black", alpha = .5) +
tm_credits("Data # Unites States Department of Agriculture\nShape # Unites States Census Bureau", position = c("right", "bottom")) +
tm_layout(title.position = c("center", "top"),
legend.position = c("right", "bottom"),
frame = FALSE,
inner.margins = c(0.1, 0.1, 0.05, 0.05))
# Alaska inset
m_AK <- tm_shape(US_AK, projection = 3338) +
tm_polygons(border.col = "grey50", border.alpha = .5, breaks = seq(10, 50, by = 5)) +
tm_layout("Alaska", legend.show = FALSE, bg.color = NA, title.size = 0.8, frame = FALSE)
# Hawaii inset
m_HI <- tm_shape(US_HI, projection = 3759) +
tm_polygons(border.col = "grey50", border.alpha = .5, breaks=seq(10, 50, by = 5)) +
tm_layout(legend.show = FALSE, bg.color=NA, title.position = c("LEFT", "BOTTOM"), title.size = 0.8, frame=FALSE)
# print insets
print(m_AK, vp=viewport(x= 0.15, y= 0.15, width= 0.3, height= 0.3))
print(m_HI, vp=viewport(x= 0.4, y= 0.1, width= 0.2, height= 0.1))
Source: I've adapted this from https://github.com/mtennekes/tmap/tree/master/demo/USChoropleth

Resources