How to make a dashed line and legend using ggplot - r

I want to know how to add a legend to my graph and also if its possible to make a line half solid half dashed.
I need the red line to become dashed at 28 and the green one at 20 I've been told to use geo_segment but I can't find a way to see the commands I need to input.
If anyone can help and suggest what codes should I use it would be great.
man<-dataset
ggplot(man,aes(Plot))+
geom_line(aes(y=N),color="forestgreen",lwd=0.5)+
geom_ribbon(aes(ymin=NLB,ymax=NUB),alpha=0.2,fill="green")+
geom_line(aes(y=M),color="navy",lwd=0.5)+
geom_ribbon(aes(ymin=MLB,ymax=MUB),alpha=0.2,fill="blue")+
geom_line(aes(y=S),color="brown1",lwd=0.5)+
geom_ribbon(aes(ymin=SLB,ymax=SUB),alpha=0.2,fill="red")+
xlab("Number of Samples")+
ylab("Number of Diametric-Species")

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
df <- data.frame(
x = seq(1:200),
y = log(seq(1:200))
)
df <- df %>% mutate(should_dash = x >= 50)
ggplot(df, aes(x,y)) + geom_line(aes(linetype = should_dash))
Created on 2018-06-15 by the reprex package (v0.2.0).

Related

Converting SpatVector objects to data frames for use in ggplot2

I would like to convert SpatVector objects to data frames for use in ggplot2.
pkgs <- c("geodata", "raster", "ggplot2", "tidy")
lapply(pkgs, require, character.only = TRUE)
boundary_GB <- geodata::gadm(country = "GB", path = tempdir(), resolution = 2, level = 1)
My current approach takes a long time:
boundary_GB_df <- broom::tidy(methods::as(boundary_GB, "Spatial"))
The plot:
ggplot(data = boundary_GB_df, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = NA, colour = "black")
I am not experienced with SpatVector objects, is there a faster approach?
I am aware of tidyterra package (i.e., tidyterra::geom_spatvector()).
Thanks
sf objects are also data.frame and you can use a specific geom provided by ggplot2 (geom_sf()). Conversion between spatial vectors classes in R is as simple as:
# From SpatVector to sf
sf::st_as_sf(x_spatvector)
# From sf to SpatVector
terra::vect(x_sf)
# To sp, although for most uses is recommended to stick to sf
as(x_sf, "Spatial")
So if ypu only need to plot the spatial object, why not use ggplot2::geom_sf()/tidyterra::geom_spatvector()? Convert the object to data frame for plotting seems to be just going back and forth, unless you have a good reason for doing that.
See reprex:
library(geodata)
#> Loading required package: terra
#> terra 1.6.17
library(ggplot2)
boundary_GB <- geodata::gadm(country = "GB", path = tempdir(), resolution = 2, level = 1)
class(boundary_GB)
#> [1] "SpatVector"
#> attr(,"package")
#> [1] "terra"
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
boundary_GB_sf <- st_as_sf(boundary_GB)
class(boundary_GB_sf)
#> [1] "sf" "data.frame"
# Is already a data.frame
# sf with geom_sf
ggplot(boundary_GB_sf) +
geom_sf(fill = NA, colour = "black")
# Spatvector with tidyterra
library(tidyterra)
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:terra':
#>
#> intersect, union
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Loading required package: tibble
#> Loading required package: tidyr
#>
#> Attaching package: 'tidyr'
#> The following object is masked from 'package:terra':
#>
#> extract
ggplot() +
geom_spatvector(data = boundary_GB, fill = NA, colour = "black")
Created on 2022-10-05 with reprex v2.0.2

How I can Speed up code built using purrr- Why is Furrr slower than purrr

I'd like to know if there is a way to speed up a code built with purrr package. I tried to convert it into furr and use the multisession option, but it is even slower than the sequential version.
# rm(list = ls())
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
#> Error: RStudio not running
getwd()
#> [1] "C:/Users/Angela/AppData/Local/Temp/RtmpOqCRC2/reprex-44604912759f-full-husky"
#load required packages
library(mc2d)
#> Loading required package: mvtnorm
#>
#> Attaching package: 'mc2d'
#> The following objects are masked from 'package:base':
#>
#> pmax, pmin
library(gplots)
#>
#> Attaching package: 'gplots'
#> The following object is masked from 'package:stats':
#>
#> lowess
library(RColorBrewer)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyverse)
library(furrr)
#> Loading required package: future
library(future) #for parallel computation
#remotes::install_github("HenrikBengtsson/parallelly", ref="develop") #to use multisession
library(parallelly)
library(tictoc)
set.seed(99)
iters<-1000
df<-data.frame(id=c(1:30),cat=c(rep("a",12),rep("b",18)),month=c(1:6,1,6,4,1,5,2,3,2,5,4,6,3:6,4:6,1:5,5),n=rpois(30,5))
df$n[df$n == "0"] <- 3
se<-rbeta(iters,96,6)
epi.a<-rpert(iters,min=1.5, mode=2, max=3)
p=0.2
p2=epi.a*p
df<-as_tibble(df)
# this defined function ensures any `n` from `df` will be itered with 10000 s and a and generated 10000 results
plan(multisession)
tic()
iter_n <- function(n) future_map2_dbl(.x = se, .y = p2, ~ 1 - (1 - .x * .y) ^ n)
list_1 <- df %>% mutate(Result = future_map(n, ~iter_n(.x))) %>% unnest(Result)%>% group_split(month)
toc()
#> 2.22 sec elapsed
plan(sequential)
#the same without parallelization
tic()
iter_n <- function(n) map2_dbl(.x = se, .y = p2, ~ 1 - (1 - .x * .y) ^ n)
list_1 <- df %>% mutate(Result = map(n, ~iter_n(.x))) %>% unnest(Result)%>% group_split(month)
toc()
#> 0.08 sec elapsed
Created on 2022-05-08 by the reprex package (v2.0.1)
I have read about an issue of using furrr with R studio (https://github.com/DavisVaughan/furrr/issues/195), so I followed the advice and downloaded the parallely package, but it doesn't change anything. Furrr is still slower than purrr (which is actually odd)
If someone is wondering what system I am using I am working with a Windows system.
Do you have any suggestion on how to speed up a code using purr or fixing the problem of furrr? This is just an example, but I have a huge database to deal with. Any suggestion is appreciated.

Defining a column as y-axis with tidygraph and ggraph? foodweb and network plots

community!
I have a question regarding tidygraph:: and ggraph:: packages.
I am trying to create a food web network plot (code and graph below), however, I wanted to use the kk layout with a defined y-axis, in my case the TL column from nodes_df.
I have created mock data to show as an example. If anybody has an idea on how to improve this plot, that would be of great help.
library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.1.2
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
#> Warning: package 'purrr' was built under R version 4.1.2
#> Warning: package 'dplyr' was built under R version 4.1.2
#> Warning: package 'stringr' was built under R version 4.1.2
library(tidygraph)
#> Warning: package 'tidygraph' was built under R version 4.1.2
#>
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#>
#> filter
library(ggraph)
#> Warning: package 'ggraph' was built under R version 4.1.2
library(igraph)
#> Warning: package 'igraph' was built under R version 4.1.2
#>
#> Attaching package: 'igraph'
#> The following object is masked from 'package:tidygraph':
#>
#> groups
#> The following objects are masked from 'package:dplyr':
#>
#> as_data_frame, groups, union
#> The following objects are masked from 'package:purrr':
#>
#> compose, simplify
#> The following object is masked from 'package:tidyr':
#>
#> crossing
#> The following object is masked from 'package:tibble':
#>
#> as_data_frame
#> The following objects are masked from 'package:stats':
#>
#> decompose, spectrum
#> The following object is masked from 'package:base':
#>
#> union
library(ggpubr)
#> Warning: package 'ggpubr' was built under R version 4.1.2
set.seed(16)
label <- c("Transient_orca",
"Salmon_sharks",
"Resident_orca",
"Sleeper_sharks",
"Halibut",
"Pinnipeds",
"Porpoise",
"Lingcod",
"Arrowtooth_L",
"Salmon_L",
"Pacific_cod",
"Sablefish",
"Arrowtooth_S",
"Spiny_dogfish",
"Avian_raptors",
"Octopods",
"Seabirds",
"Deep_demersals",
"Pollock_L",
"Rockfish",
"Baleen_whales",
"Salmon_fry_S",
"Nshore_demersal",
"Squids",
"Eulachon",
"Sea_otters",
"Deep_epibenthos",
"Capelin",
"Herring_L",
"Pollock_S",
"Invert_eat_seaduck",
"Oystercatchers",
"Sandlance",
"Sunflower_stars",
"Pisaster_Evasterias",
"Leather_stars",
"Sea_cucumbers",
"Urchins",
"Helmet_crab",
"Herring_S",
"Jellies",
"Deep_infauna_S",
"Zoopl_near_onmiv",
"Zoop_omniv",
"Shallow_infauna_S",
"Meiofauna",
"Deep_infauna_L",
"Snail_crust_S",
"Mussels",
"Barnacles",
"Shallow_infauna_clams",
"Zoopl_near_herb",
"Zoopl_herb",
"Phyto_near",
"Phyto_off",
"Fucus",
"Subtidal_kelps",
"Macroalgae_other",
"Eelgrass",
"Nekton_falls",
"Inshore_detritus",
"Offshore_detritus",
"Salmon_seine","Salmon_gillnets",
"Herring_seine","Shrimp_pot_trawl","Pollock_trawl" ,"Demersal_longline" ,
"Other_commercial","Rec_anglers","Rec_charters", "Subsistence_take")
TL <- rnorm(72, 3.155, 1)
B <- abs(rnorm(72, 0.7789, 10))
nodes_df <-data.frame(label,TL, B)
from <- rep(c("Lingcod",
"Arrowtooth_L",
"Salmon_L",
"Pacific_cod",
"Sablefish",
"Arrowtooth_S",
"Spiny_dogfish",
"Avian_raptors",
"Octopods",
"Seabirds",
"Deep_demersals",
"Pollock_L",
"Rockfish",
"Baleen_whales",
"Salmon_fry_S",
"Nshore_demersal",
"Squids",
"Eulachon",
"Sea_otters",
"Deep_epibenthos",
"Capelin",
"Herring_L",
"Pollock_S",
"Invert_eat_seaduck",
"Oystercatchers",
"Sandlance",
"Sunflower_stars",
"Pisaster_Evasterias",
"Leather_stars",
"Sea_cucumbers",
"Urchins",
"Helmet_crab",
"Herring_S",
"Jellies",
"Deep_infauna_S",
"Zoopl_near_onmiv",
"Zoop_omniv",
"Shallow_infauna_S",
"Meiofauna",
"Deep_infauna_L",
"Snail_crust_S",
"Mussels",
"Barnacles",
"Shallow_infauna_clams",
"Zoopl_near_herb",
"Zoopl_herb",
"Phyto_near",
"Phyto_off",
"Fucus",
"Subtidal_kelps",
"Macroalgae_other",
"Eelgrass",
"Nekton_falls",
"Inshore_detritus",
"Offshore_detritus"), times= 3)
to <- sample(label, size = 165, replace = TRUE)
width <- abs(rnorm(165, 0.258370, 10))
edge_df <- as_tibble(data.frame(from, to,width))
netgraph_df <- graph_from_data_frame(d=edge_df, vertices = nodes_df, directed=T)
graph <- as_tbl_graph(netgraph_df)
# plot using ggraph
ggraph(graph, layout = 'kk') +
geom_edge_link(aes(edge_width = width, color=stat(index)), lineend="round")+
scale_edge_colour_gradient(high = "#e96d50", low = "#4b84a6") +
scale_edge_width(range = c(0.5, 5)) +
geom_edge_loop(aes(edge_width = width, color=stat(index)), lineend="round")+
geom_node_point(aes(col= nodes_df$TL, size = nodes_df$B)) +
geom_node_text(aes(label = label), size=3,color="black", repel = TRUE) +
theme_transparent()+
theme(legend.position = "none")
Created on 2022-02-03 by the reprex package (v2.0.1)
You can precalculate the layout and set the y column to some metric.
# Same prep as in question
graph <- as_tbl_graph(netgraph_df)
lay <- create_layout(graph, "kk")
lay$y <- lay$TL
# plot using ggraph
ggraph(graph = lay) +
geom_edge_link(aes(edge_width = width, color=stat(index)), lineend="round")+
scale_edge_colour_gradient(high = "#e96d50", low = "#4b84a6") +
scale_edge_width(range = c(0.5, 5)) +
geom_edge_loop(aes(edge_width = width, color=stat(index)), lineend="round")+
geom_node_point(aes(col= nodes_df$TL, size = nodes_df$B)) +
geom_node_text(aes(label = label), size=3,color="black", repel = TRUE) +
theme_transparent()+
theme(legend.position = "none")

Error when using curly-curly (`{{ }}`) operator with `if` clause

I'm struggling to understand how to use the {{ }} operator to pass bare variable names in custom functions. I get an error when I use the operator in conjunction with an if clause.
This function works:
f <- function(.data, .vars=NULL){
require(dplyr)
df = select(.data, {{ .vars }})
print(head(df))
}
f(iris, c(Species, Sepal.Length))
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Species Sepal.Length
#> 1 setosa 5.1
#> 2 setosa 4.9
#> 3 setosa 4.7
#> 4 setosa 4.6
#> 5 setosa 5.0
#> 6 setosa 5.4
Created on 2021-12-20 by the reprex package (v2.0.1)
If I try to add an if clause, it throws an error:
f <- function(.data, .vars=NULL){
require(dplyr)
if(!is.null(.vars)) df = select(.data, {{ .vars }})
else df = .data
print(head(df))
}
f(iris, c(Species, Sepal.Length))
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Error in f(iris, c(Species, Sepal.Length)): object 'Species' not found
Created on 2021-12-20 by the reprex package (v2.0.1)
What am I missing?
I think the easiest explanation is that when .vars is not NULL, R will interpret the value (in your example: c(Species, Sepal.Length)) as a vector of variables, and look for these variables in your environment. Since you don't have any variable called Species, it throws an error.
You can fix it like this:
library(dplyr)
f <- function(.data, .vars = NULL){
vars <- enquo(.vars)
if(!rlang::quo_is_null(vars)) df = select(.data, !!vars)
else df = .data
print(head(df))
}
f(iris)
f(iris, c(Species, Sepal.Length))
Note that {{x}} is actually a shorthand for !!enquo(x).
Elaboration (update)
When you don't use if, the only place .vars is being used is inside dplyr::select(.data, {{.vars}}). In this context, the variable names in .vars are interpreted as being variables in the dataframe .data.
When you add the if statement, the .vars is evaluated as being variables in your environment. Since they don't exist in your environment you get an error.
This is called data-masking.
Here is a
nice article about it.
#jpiversen's answer and explanation are correct, but here's a simpler fix for your function. Instead of looking for the default value of NULL, just check if .vars is missing:
library(dplyr)
f <- function(.data, .vars){
if(!missing(.vars)) df = select(.data, {{ .vars }})
else df = .data
print(head(df))
}
f(iris, c(Species, Sepal.Length))
By the way, I also removed require(dplyr) from your function. It's generally a bad idea to use it in a function, because of the side effect of changing the search list. Use requireNamespace("dplyr") and prefix functions using dplyr:: if you're not sure it will be available.

Unable to plot heat map

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
Apartment_no <- c("1-SV","1-SV","1-SV","1-SH","1-SH","1-SH","1-1V","1-1V","1-1V","1-1H","1-1H","1-1H","3-SV","3-SV","3-SV","3-1V","3-1V","3-1V","3-1H","3-1H","3-1H")
month <- c("September","October","November","September","October","November","September","October","November","September","October","November","September","October","November","September","October","November","September","October","November")
Days <- c(NA,19,28,2,19,28,2,19,NA,2,19,28,25,31,28,12,NA,24,8,26,19)
Heat_clean <- data.frame(Apartment_no,month,Days)
This is just a sample dataset. In actual, I have around 163 apartment_no and all the months of data. I wish to create an interactive heatmap for it since the data is quite big. I wish to use a special color code i.e whenever the Days==NA, color=Red,1<=Days<=5,color=Blue,6<=Days<=15,color=Orange,16<=Days<=25,color=Pink, 25<=Days<=31,color=Green. I have used the following code but it is not working for me & infact giving me an error message as "`x' must be a numeric matrix". My code is as follows:
> mypallete <- colorRampPalette(Days=na.color,col="Red", 1<=Days<=5,col="Blue", 6<=Days<=15,col="Orange", 16<=Days<=25,col="Pink", 25<=Days<=31,color=Green)
> heatmap.2(as.matrix(Heat_clean),Rowv = F,Colv = F,main = "Heatmeters data",col = mypallete,dendrogram = "none",density.info = "none",trace = "none")
I first defined my own pallete & then implemented it in my code. I wish to get something that can be seen in figure, though with my personalised color coding. Maybe later I can insert the code in plot_ly to get it interactive.
Your ranges are not exclusive (Days <= 25 and 25 <= Days) but that is easily fixed...
I don't think the structure of your data matches what heatmap.2 is expecting, and that is what is giving you the error, not the color map.
Here is one brute-force way to generate the color palette... (note I changed the spelling of mypalette)
mypalette=rep("Green",length(Days))
mypalette[Days <= 25] = "Pink"
mypalette[Days <= 15] = "Orange"
mypalette[Days <= 5] = "Blue"
mypalette[is.na(Days)] = "Red"

Resources