Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created May 28, 2019 16:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjmahr/23e72154b6906bb8c8da1f942b70664c to your computer and use it in GitHub Desktop.
Save tjmahr/23e72154b6906bb8c8da1f942b70664c to your computer and use it in GitHub Desktop.
chess moves
library(tidyverse)
theme_set(theme_minimal())

mt <- read.csv(url('https://gist.githubusercontent.com/ashtonanderson/cfbf51e08747f60472ee2132b0d35efb/raw/80acd2ad7c0fba4e85c053e61e9e5457137e00ee/moveno_piecetype_counts'))

mt$piece_type <- factor(
  mt$piece_type, 
  levels = c("P","N","B","Q","R","O","K"),
  labels = c(
    "Pawn", "Knight", "Bishop", "Queen", "Rook", "Castling", "King"
  )
)

mt <- mt %>%
  group_by(move_number) %>% 
  mutate(
    tot = sum(count), 
    frac = count / tot
  ) %>% 
  ungroup()

areas <- mt %>% 
  as_tibble() %>% 
  arrange(move_number, desc(piece_type)) %>% 
  group_by(move_number) %>% 
  mutate(
    upper_frac = cumsum(frac),
    lower_frac = upper_frac - frac 
  ) %>% 
  ungroup() 

labels1 <- areas %>% 
  group_by(piece_type) %>% 
  filter(50 < move_number, move_number < 100) %>% 
  filter(frac == max(frac)) %>% 
  filter(piece_type != "Castling")

labels2 <- areas %>% 
  group_by(piece_type) %>% 
  filter(frac == max(frac)) %>% 
  filter(piece_type == "Castling")

ggplot(mt %>% filter(move_number <= 125), aes(move_number)) + 
  geom_area(
    aes(y = count / tot, fill = piece_type), 
    position = 'fill'
  ) +
  geom_text(
    aes(y = (upper_frac + lower_frac) / 2, label = piece_type),
    data = labels1
  ) +
  ggrepel::geom_text_repel(
    aes(y = (upper_frac + lower_frac) / 2, label = piece_type),
    data = labels2,
    nudge_x = 6, 
    nudge_y = .05,
    hjust = 0
  ) + 
  guides(fill = FALSE) +
  scale_x_continuous(
    "Move Number", 
    limits = c(1, 125),
    expand = expand_scale(0, 0)
  ) +
  scale_y_continuous(
    NULL,
    labels = scales::percent, 
    breaks = seq(0, 1, 0.2), 
    limits = c(0, 1),
    expand = expand_scale(0, 0)
  ) +
  scale_fill_brewer(
    type = 'qual',
    palette = 3,
    name = 'Piece type'
  ) + 
  theme(
    axis.ticks = element_line(), 
    plot.margin = margin(8, 8, 8, 8, unit = "pt")
  )

Created on 2019-05-28 by the reprex package (v0.3.0)

@paoloinglese
Copy link

Fantastic!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment