R语言 使用ggplot生成较小矩形时出现问题

polhcujo  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(111)

我想减少矩形的大小,看到下面的图片,他们是大的。如果我将geom_rect中的xminxmaxyminymax调整为较小的值,例如.2,则图形未格式化,矩形被分隔开。如何继续?

library(tidyverse)

df <- bind_rows(
  expand_grid(x = 1:5, y = c(1, 2.2)),
  expand_grid(x = 8:12, y = c(1, 2.2))
) %>%
  arrange(y, x) %>%
  mutate(
    num = c(c(1, 0, 1, 1, 0), c(1, 0, 0, 1, 0), c(0, 1, 0, 1, 0), c(0, 1, 1, 1, 0)),
    fill_color = ifelse(row_number() %in% c(c(11,12,13,14,15), c(16,17), c(8,9,10)), "skyblue", "white")
  )

ggplot(df) +
  geom_rect(aes(xmin = x - .5, xmax = x + .5, ymin = y - .5, ymax = y + .5, fill = fill_color), color = "black") +
  geom_text(aes(x = x, y = y, label = num)) +
  geom_segment(aes(x = 2.5, xend = 2.5, y = .4, yend = 2.8), arrow = arrow(length = unit(5, "pt"))) +
geom_segment(
    aes(x = 5.7, xend = 7.3, y = 1.6, yend = 1.6),
    linewidth = 3, lineend = "round", linejoin = 'round', color = "black",
    arrow = arrow(length = unit(9, "pt"), type = "open")
  ) +
  scale_fill_manual(values = c("skyblue", "white")) +
  ylim(0, 4) +
  xlim(0, 13) +
  theme_void() + theme(
    panel.background = element_rect(fill = 'white'),
    plot.margin = unit(c(0, 0, 0, 0), "pt"),
    legend.position = "none"
  )

nx7onnlm

nx7onnlm1#

一个选项是使用coord_cartesian更改限制,使图形看起来更小,如下所示:

library(tidyverse)

ggplot(df) +
  geom_rect(aes(xmin = x - .5, xmax = x + .5, ymin = y - .5, ymax = y + .5, fill = fill_color), color = "black") +
  geom_text(aes(x = x, y = y, label = num)) +
  geom_segment(aes(x = 2.5, xend = 2.5, y = .4, yend = 2.8), arrow = arrow(length = unit(5, "pt"))) +
geom_segment(
    aes(x = 5.7, xend = 7.3, y = 1.6, yend = 1.6),
    linewidth = 3, lineend = "round", linejoin = 'round', color = "black",
    arrow = arrow(length = unit(9, "pt"), type = "open")
  ) +
  scale_fill_manual(values = c("skyblue", "white")) +
  theme_void() + theme(
    panel.background = element_rect(fill = 'white'),
    plot.margin = unit(c(0, 0, 0, 0), "pt"),
    legend.position = "none"
  ) +
  coord_cartesian(xlim = c(0, 15),
                  ylim = c(0, 5))

创建于2023-06-15带有reprex v2.0.2

相关问题