R语言 ggplot2热图上的硬编码bin位置

5lwkijsr  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(173)

我想硬编码bin位置,以匹配geom_rect内的9个矩形,并忽略矩形外的所有结果。

library(ggplot2)
library(dplyr)

# Replace directory below
pitcher_data <- read.csv("stackoverflow.csv")

ggplot(data = pitcher_data, aes(x = PlateLocSide, y = PlateLocHeight)) +
  ylim(0, 4) +
  xlim(-3, 3) +
  geom_bin2d(aes(fill = stat(count)), binwidth = c(0.8, 0.6)) +
  scale_fill_gradientn(colors = c("#3661ad", "white", "#d82129"),
                       values = c(0, .5, 1)) +
  geom_segment(aes(x = -0.4, xend = -0.4, y = 1.3, yend = 3.1), color = "lightgray", linetype = "dashed") + 
  geom_segment(aes(x = 0.4, xend = 0.4, y = 1.3, yend = 3.1), color = "lightgray", linetype = "dashed") +
  geom_segment(aes(x = -1.20, xend = 1.20, y = 1.9, yend = 1.9), color = "lightgray", linetype = "dashed") + 
  geom_segment(aes(x = -1.20, xend = 1.20, y = 2.5, yend = 2.5), color = "lightgray", linetype = "dashed") +
  geom_rect(xmin = -1.20, xmax = 1.20, ymin = 1.30, ymax = 3.1, show.legend = FALSE, fill = "transparent", color = "black") +
  theme_classic() +
  xlab("Plate Side (ft)") +
  ylab("Plate Height (ft)") +
  labs(fill = "Count", title = "Pitch Heatmap") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_fixed(ratio = 2)

Google Sheet CSV link
我试着调整箱子的宽度和长度,但这只是从现有的位置调整它们,并没有把它们作为一个整体移动。

z9ju0rcb

z9ju0rcb1#

我想您可以使用cutfindInterval手动bin,然后使用geom_tile

library(tidyverse)

pitcher_data %>%
  mutate(bin_x = findInterval(PlateLocSide, c(-1.2, -0.4, 0.4, 1.2)) + 1,
         bin_x = c(-0.8, 0, 0.8)[bin_x],
         bin_y = findInterval(PlateLocHeight, c(1.3, 1.9, 2.5, 3.1)) + 1,
         bin_y = c(1.6, 2.2, 2.8)[bin_y]) %>%
  filter(complete.cases(.)) %>%
  group_by(bin_x, bin_y) %>%
  summarise(count = n(), .groups = "drop") %>%
  ggplot(aes(x = bin_x, y = bin_y, fill = count)) +
  ylim(0, 4) +
  xlim(-3, 3) +
  geom_tile() +
  scale_fill_gradientn(colors = c("#3661ad", "white", "#d82129"),
                       values = c(0, .5, 1)) +
  annotate("segment", color = "lightgray", linetype = "dashed",
           x = c(-0.4, 0.4, -1.2, -1.2),
           xend = c(-0.4,0.4, 1.2, 1.2), 
           y = c(1.3, 1.3, 1.9, 2.5),
           yend = c(3.1, 3.1, 1.9, 2.5)) + 
  geom_rect(xmin = -1.20, xmax = 1.20, ymin = 1.30, ymax = 3.1, 
            show.legend = FALSE, fill = "transparent", color = "black") +
  theme_classic() +
  xlab("Plate Side (ft)") +
  ylab("Plate Height (ft)") +
  labs(fill = "Count", title = "Pitch Heatmap") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_fixed(ratio = 2)

相关问题