Skip to content

Instantly share code, notes, and snippets.

@noamross
Forked from ottlngr/keystrokes.R
Created March 21, 2016 16:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save noamross/156a79bb9ce5eb6f0680 to your computer and use it in GitHub Desktop.
Visualizing keystrokes using ggplot2
##### Visualizing keystrokes using ggplot2 #####
library(ggplot2)
# a character string to visualize:
string <- 'R is an integrated suite of software facilities for data manipulation, calculation and graphical display.'
# a data.frame representing the keys of a qwerty keyboard
qwerty <- data.frame(
id = 1:47,
xmin = c(1:10, seq(0.5,0.5+10,1), seq(0.3,0.3+12,1), seq(-1.2, -1.2+12,1)),
xmax = c(2:11, seq(1.5,1.5+10,1), seq(1.3, 1.3+12,1), seq(-0.2, -0.2+12,1)),
ymin = c(rep(1,10), rep(2,11), rep(3,13), rep(4,13)),
ymax = c(rep(2,10), rep(3,11), rep(4,13), rep(5,13))
)
# a data.frame to map the characters to the respective key (qwerty)
qwerty_map <- data.frame(id = c(1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 20, 21, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47),
sym = c('z','x','c','v','b','n','m',',','<','.','>','/','?','a','s','d','f','g','h','j','k','l',';',':',"'",'"','q','w','e','r','t','y','u','i','o','p','[','{',']','}','\\','|','`','~','1','!','2','@','3','#','4','$','5','%','6','^','7','&','8','*','9','(','0',')','-','_','=','+'))
# split the string in single characters
chars <- unlist(strsplit(string, split=NULL))
# get character frequencies
freq <- as.data.frame(table(chars))
# prepare the 'map'
map <- cbind(qwerty_map, Freq = 0)
map <- merge(map, freq, by.x="sym", by.y="chars", all=T) # capitals get lost here. Either include capitals in ``qwerty_map`` or transform ``chars`` to lower case only.
map$Freq <- ifelse(is.na(map$Freq.y), map$Freq.x, map$Freq.y)
map$Freq.x <- NULL
map$Freq.y <- NULL
# merge coordinates (``qwerty``) and actual data (``map``)
map <- merge(qwerty, map, by="id")
# plot
ggplot() +
geom_rect(aes(xmin=map$xmin, xmax=map$xmax,ymin=map$ymin,ymax=map$ymax, fill=map$Freq), colour="black", size=2) +
scale_fill_gradient(low="white", high="red")
### To do: handle capitals
### mark the keys with the respective letter or symbol(s)
### add missing keys to the plot (to look like an actual keyboard)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment