Skip to content

Instantly share code, notes, and snippets.

@timriffe
Created July 19, 2018 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriffe/6c973a3c6ff3823bfc5ed4caed5dfd35 to your computer and use it in GitHub Desktop.
Save timriffe/6c973a3c6ff3823bfc5ed4caed5dfd35 to your computer and use it in GitHub Desktop.
example code for getting surfaces with some good properties.
load("/home/tim/Desktop/Hom_viv_muj.rdata")
ls()
library(RColorBrewer)
# select a suitable ramp (sequential for rates, divergent for differences or ratios)
# display.brewer.all()
ramp <- colorRampPalette(brewer.pal(9, "RdPu"), space = "Lab")
years <- 2000:2017
ages <- c(0,1,seq(5,105,by=5))
# probably log rates, but not necessarily for homicide.
breaks <- pretty(MxF_hom[ages[1:nrow(MxF_hom)] <= 80,], n = 20)
# give it a ceiling
breaks <- c(breaks,max(range(pretty(MxF_hom))))
# gives good breaks for absolutes, not so good for log
pdf("test.pdf")
par(mfrow=c(1,3))
# surf 1
image( x = years,
y = ages,
t(MxF_hom),
breaks = breaks, # breaks from above
col = ramp(length(breaks) - 1), # one less color than there are intervals
asp = 1) # age = time
contour( x = 2000.5:2016.5, # midpoints!!
y = c(.5,3,seq(7.5,102.5,by=5)),
t(MxF_hom),
add = TRUE) # draws on top
# surf 2
image( x = years,
y = ages,
t(MxF_hom),
breaks = breaks,
col = ramp(length(breaks) - 1),
asp = 1)
contour( x = 2000.5:2016.5,
y = c(.5,3,seq(7.5,102.5,by=5)),
t(MxF_hom),
add = TRUE)
# surf 3
image( x = years,
y = ages,
t(MxF_hom),
breaks = breaks,
col = ramp(length(breaks) - 1),
asp = 1)
contour( x = 2000.5:2016.5,
y = c(.5,3,seq(7.5,102.5,by=5)),
t(MxF_hom),
add = TRUE)
dev.off()
library(MortalitySmooth)
# use Mort1Dsmooth()
# https://www.rdocumentation.org/packages/MortalitySmooth/versions/2.3.4/topics/Mort1Dsmooth
# suggestion: do image() on raw data, as above, but draw contours based on the smoothed surface,
# where each year is smoothed independently. Reason: there are ruptures to preserve.
# for ratios visualize the log,
# before:
hist(runif(100)/runif(100),n=20)
# after: ( < 0 after logging = < 1 of ratio).
# now negatives are on same scale as positives, and even steps are *proportional*
hist(log(runif(100)/runif(100)),n=20)
# choose breaks from this:
# however, to get good breaks, you can think in the analog:
example_breaks <- c(1/1000,1/100,1/10,1,10,100,1000)
# for log ratios, you probably won't go as big as 1000, but you'll want to think in terms of
# equal jumps in any case, mirrored. Then you can use these as absolute breaks for colors
# and contours.
# 2) choose a ramp that is DIVERGENT, and make sure the neutral midpoint color is on 0,
# You can get that by have the same number and spread of low and high values, like
# the above example.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment