ggplot:如何将网格线与geom_tile的末尾对齐

5
我正在尝试使用ggplots geom_tile创建热力图。目前,网格线位于每个geom_tile的中心。我希望网格线与每个瓷砖的起始/结束位置对齐。我看到了一些相关的帖子(这里这里),但都涉及连续比例尺。在我的情况下,两个比例尺都是离散/因子。有什么想法吗?非常感谢!
library(tidyverse)

my_iris <- iris %>% 
  mutate(sepal_interval=cut(Sepal.Length, 4)) %>% 
  group_by(sepal_interval, Species)

my_iris %>% 
  summarise(n_obs=n()) %>% 
  ggplot()+
  geom_tile(aes(y=Species,
                x=sepal_interval,
                fill=n_obs))+
  theme_bw()+
  theme(panel.grid = element_line(color="black"))

这段内容是由reprex包 (v0.3.0)在2020年1月28日创建的。


添加类似于这个链接中的水平和垂直线条:https://dev59.com/52Af5IYBdhLWcg3w9mps,是否有帮助? - Valeri Voev
2个回答

6

我在使用ggplot2中的geom_rect制作热图时非常成功。虽然前端需要进行更多的数据精细处理,但我发现它更加灵活且易于定制。

my_iris <- iris %>% 
  mutate(sepal_interval=cut(Sepal.Length, 4)) %>% 
  group_by(sepal_interval, Species) %>% 
  summarise(n_obs=n()) %>%
  mutate(sepal.id = as.numeric(as.factor(sepal_interval)),
         species.id = as.numeric(as.factor(Species)))

species.key <- levels(factor(my_iris$Species))
sepal.int.key <- levels(factor(my_iris$sepal_interval))

my_iris %>%
  ggplot() +
  geom_rect(aes(xmin = sepal.id, xmax = sepal.id+1, ymin = species.id, ymax = species.id+1, fill = n_obs)) +
  theme_bw() +
  scale_x_continuous(breaks = seq(1.5, length(sepal.int.key)+0.5, 1), labels = sepal.int.key, expand = c(0,0)) +
  scale_y_continuous(breaks = seq(1.5, length(species.key) + 0.5, 1), labels = species.key, expand = c(0,0)) +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        panel.ontop = TRUE,
        panel.background = element_rect(fill = "transparent"))


使用以下代码输出: 输入图片描述

0

我相信你正在寻找某种变体:

my_iris %>% 
  summarise(n_obs=n()) %>% 
  ggplot()+
  geom_raster(aes(y=Species,
                  x=sepal_interval,
                  fill=n_obs), 
              hjust =0,
              vjust =0)+
  theme_bw()+
  theme(panel.grid = element_line(color="black")) 

我不相信hjustvjust参数适用于geom_tile,但在帮助页面中使用的是geom_rasterhjustvjust的值应该介于0和1之间,它们都默认为0.5,这使它们居中于该点。


非常感谢。它非常接近,但不幸的是据我所见,标签并没有居中于矩形的中心,而是位于断点/线上。似乎使用theme(axis.text=element_text(hjust=0.5)等可以有所帮助,但并不能完全解决问题。 - zoowalk
从您发布的链接中,我认为您希望标签与每个瓷砖的网格线对齐。不幸的是,在离散比例尺上制作网格线没有简单的方法,您需要使用连续比例尺手动添加它们。 - Justin Landis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接