Using BFAST to show breakpoints - r

I am currently working with bfastSpatial, I am attempting to plot breakpoint values as a year colour based legend. I am aware of changeMonth function for plotting monthly based breakpoints (http://www.loicdutrieux.net/bfastSpatial/) however, I am attempting to achieve a similar outcome as in Morrison et al. (2019) https://www.mdpi.com/2072-4292/10/7/1075
Any assistance would be appreciated.

If you want to round the breakpoint dates to integer years, you can use floor, as the dates are in decimal years. Next, to make a similar plot as the one you showed, you can use the tmap package. Since you did not attach any data to the OP, I used the tura data included in the bfastSpatial package.
library(bfastSpatial)
library(tmap)
# Load tura data
data(tura)
# Perform bfast analysis
bfm <- bfmSpatial(tura, start=c(2009, 1), order=1)
# Extract the first band (breakpoints)
change <- bfm[[1]]
# As breakpoints dates are in year decimals,
# you can use floor to round them to lowest integer
change <- floor(change)
# Set shape as change, the object to plot
tm_shape(change) +
# Plot it as raster and set the palette, number of categories,
# style (categorical) and title of the legend.
tm_raster(palette = "Spectral",
n = 5,
style = "cat",
title = "Year") +
# Set the legend's position and eliminate the comma used by default for
# separating thousands values. Add background color and transparency
tm_layout(legend.position = c("right", "bottom"),
legend.format=list(fun=function(x) formatC(x, digits=0, format="d")),
legend.bg.color = "white",
legend.bg.alpha = 0.7) +
# Add scale bar, set position and other arguments
tm_scale_bar(breaks = c(0,0.5,1),
position = c("right", "top"),
bg.color = "white",
bg.alpha = 0.7) +
# Add north arrow with additional parameters
tm_compass(type = "arrow",
position = c("left", "top"),
bg.color = "white",
bg.alpha = 0.7)
The obtained plot:

Related

R ::tmap plot and display NA values in legend

I want to map point data with results of bird counts. The point size should be scaled according to the number of birds that were counted. If an area has not been counted an x should be displayed for NA values. How do I plot these data and reach a nice legend with the tmap package?
This is a similar example:
rm(list=ls(all=TRUE))
library(tmap)
data(World, metro)
# put population size pop2020 to NA for some cities
metro$pop2020[10:300] <- NA
# add column with code for the shape of the symbol (21 for data available, 4 for NA)
metro$shape_symbol <- 21
metro[is.na(metro$pop2020), ]$shape_symbol <- 4
tm_shape(World) + tm_fill()+
tm_shape(metro) +
tm_symbols(
size = "pop2020",
col = "black",
shape = "shape_symbol", # use column shape_symbol in metro for the symbol
# shapeNA = "4", # should plot NA as cross by default - didnĀ“t work for me
title.size = "subtitle",
legend.size.is.portrait=TRUE) +
tm_layout(legend.bg.color = "gray",
legend.frame = "black")
Which gives this output. Why are the NA values not shown? And how do I reach a nice legend output?
My aim is to reach this:
The name of the bird species should be given as bold legend title with an additional label "Anzahl" for the legend symbols below. Ideally the symbol x for NA should be place like this. I can paste(i) from a loop as legend title with title.size but how do I get a second title in the legend.
Additional question: can I set the size of the points to a certain range? So that very small numbers have a minimum size in the map?
I solved it myself using a workaround:
I added an extra layer and selected only the data with missing values. Then I added an additional legend element using tm_add_legend.
data(World, metro)
# put population size pop2020 to NA for some cities
metro$pop2020[10:300] <- NA
tm_shape(World) + tm_fill()+
tm_shape(metro) +
tm_symbols(
size = "pop2020",
col = "black",
title.size = "subtitle",
legend.size.is.portrait=TRUE) +
tm_shape(metro[is.na(metro$pop2020),]) +
tm_dots(shape=4, size = 0.5, border.lwd = 0.5) +
tm_layout(legend.bg.color = "gray",
legend.frame = "black") +
tm_add_legend(type="symbol", shape =4, labels = "not available", size = 0.5, border.lwd = 0.5, col = "black")

How can I adjust the dimension of the axes fviz_pca

I'm trying to put the two axes of my biplot exactly equally scaled (i.e., 1 cm on the vertical axis must represent the same 1 cm on the horizontal axis). How can I do that with fviz_pca? or there is some better pca package?
My code
fviz_pca_ind(res.pca,
col.ind = groups, # color by groups
palette = c("#00AFBB", "#FC4E07"),
addEllipses = TRUE, # Concentration ellipses
ellipse.type = "convex",
legend.title = "Groups",
repel = T, ggtheme=theme(axis.text=element_text(size=16), axis.title=element_text(size=16)))
As the fviz function works based on ggplot2 you just need to add the information of axis lenght at the end of the funtion like this:
fviz_pca_biplot(scaptotrigona.pca,[...]) +xlim(-1, 1) + ylim (-1, 1)
remember that the values inside the "xlim()" and "ylim()" mus be equals, if you use "xlim(-1, 5)" for example, it won't work.

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.

Fine tuning addADX() to avoind truncating the trend curves

I am using the following code to look at the past 9 months of a stock.
library(quantmod)
getSymbols("AMZN")
candleChart(to.weekly(AMZN),multi.col=TRUE,theme="white",subset='last 9 months')
addADX()
You can see that the red line is essentially not included in the plot because it mostly lies below the value of 20. I want to modify the Y axis range of addADX so that it always shows all three lines. How would it be possible?
The input parameters of addADX() only control the computation of the directional movement index - not the graphical parameters which are set according to the average direction index.
A simple workaround to display the positive and negative direction index completely is to compute the directional movement index by yourself with ADX() from the TTR package and then add it to the previous chart with addTA(), which allows more customisation.
library(quantmod)
getSymbols("AMZN")
dat <- to.weekly(AMZN)
candleChart(dat, multi.col = TRUE, theme = "white", subset = "last 9 months")
adx <- ADX(HLC(dat), n = 14, maType = "EMA", wilder = TRUE)[, c("DIp", "DIn", "ADX")]
addTA(adx, col = c("green", "red", "blue"), lwd = c(1, 1, 2), legend = NULL)

dotplot dot not showing up and format of dot plot

How can I show the dots colored using the mosaic package to do a dotplot?
library(mosaic)
n=500
r =rnorm(n)
d = data.frame( x = sample(r ,n= 1,size = n, replace = TRUE), color = c(rep("red",n/2), rep("green",n/2)))
dotPlot(d$x,breaks = seq(min(d$x)-.1,max(d$x)+.1,.1))
right now all the dots are blue but I would like them to be colored according to the color column inthe data table
If you are still interested in a mosaic/lattice solution rather than a ggplot2 solution, here you go.
dotPlot( ~ x, data = d, width = 0.1, groups = color,
par.settings=list(superpose.symbol = list(pch = 16, col=c("green", "red"))))
resulting plot
Notice also
as with ggplot2, the colors are not determined by the values in your color variable but by the theme. You can use par.settings to modify this on the level of a plot or trellis.par.set() to change the defaults.
it is preferable to use a formula and data = and to avoid the $ operator.
you can use the width argument rather than breaks if you want to set the bin width. (You can use the center argument to control the centers of the bins if that matters to you. By default, 0 will be the center of a bin.)
You need to add stackgroups=TRUE so that the two different colors aren't plotted on top of each other.
n=20
set.seed(15)
d = data.frame(x = sample(seq(1,10,1), n, replace = TRUE),
color = c(rep("red",n/2), rep("green",n/2)))
table(d$x[order(d$x)])
length(d$x[order(d$x)])
binwidth= 1
ggplot(d, aes(x = x)) +
geom_dotplot(breaks = seq(0.5,10.5,1), binwidth = binwidth,
method="histodot", aes(fill = color),
stackgroups=TRUE) +
scale_x_continuous(breaks=1:10)
Also, ggplot uses its internal color palette for the fill aesthetic. You'd get the same colors regardless of what you called the values of the "color" column in your data. Add scale_fill_manual(values=c("green","red")) if you want to set the colors manually.

Resources