r - 如何在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 的图形语法。
解决方案
我不确定这段代码是否有用。通过使用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"))
推荐阅读
- c++ - 键值映射中的部分查找,其中键本身是键值映射
- vuejs2 - 为什么第一次访问时没有调用激活的生命周期挂钩
- typescript - 笑话 TypeScript 类“没有重载需要 1 个类型参数”
- sql - 选择邮政编码并放入新列
- selenium-chromedriver - 如何在 beforeSession webdriverIO+Cucumber 中从 chromeOptions 设置参数
- android - 为什么 Kendo Dropdownlist 不适用于 chrome for android?
- c# - DataGrid DateTime IValueConverter,仅编辑时间,保留日期
- python - python中的多个循环
- php - 什么是在 PHP7 中使用匿名类的好例子
- mysql - 如果不满足条件,我如何在选定范围内包含上一行