首页 > 解决方案 > 如何在ggplot中向轴添加超类别?

问题描述

我正在尝试制作一个在一个轴上具有多个分类级别的热图,即将理想、优质和非常好的钻石标记为“好”,而“好”和“一般”的钻石只是“正常”。

我知道我可以使用颜色,但我希望它以黑白方式工作,我不能使用sec_axis,因为它不是一对一的映射。(我尝试使用scale_y_discrete(sec.axis = sec_axis(rating))sec.axis = rating但都给了我一个未使用的参数错误。)

以下是一些具有代表性的数据以及用于制作常规热图的代码:

library(ggplot2)

diamond_rating <- tibble(cut = factor("Fair", "Good", "Very Good", "Premium", "Ideal"), rating = c("OK", "OK", "Great", "Great", "Great"))

diamonds %>% 
  count(color, cut) %>%  
  left_join(diamond_rating) %>%
  ggplot(mapping = aes(x = color, y = cut)) +
    geom_tile(mapping = aes(fill = n))

但我不知道如何添加一个超轴,甚至不知道它应该如何/在哪里适合 ggplot2 的图形语法。

标签: rggplot2

解决方案


我不确定这段代码是否有用。通过使用facet_wrap和一些调整,theme你可以得到一个带有超类别的图表。

diamond_rating <- tibble(cut = c("Fair", "Good", "Very Good", "Premium", "Ideal"), rating = c("OK", "OK", "Great", "Great", "Great"))

library(ggplot2)

diamonds %>% 
  count(color, cut) %>%  
  left_join(diamond_rating) %>%
  ggplot(mapping = aes(x = color, y = cut)) +
  geom_tile(mapping = aes(fill = n)) +
  facet_wrap(~rating, scales = "free_y", nrow = 2, strip.position = "left") +
  theme_classic() +
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        panel.spacing = unit(0, "lines"),
        axis.line = element_line(colour = "grey")) 

在此处输入图像描述


推荐阅读