我想对 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)
我尝试调整 bin 的宽度和长度,但它只是从现有位置调整它们,并没有将它们作为一个整体移动。
我想你可以手动使用
cut
或 findInterval
然后使用 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)