r - 包含分类数据和大量注释的反向 x 轴
问题描述
我正在研究一个创建复杂ggplot
图形的函数。除了条形图中的一些分类数据外,该图还有数十个文本和矩形注释。我想创建一个在某些情况下反转 x 轴的选项。因此,如果打开该选项,我需要添加一些逻辑来翻转轴。但是我遇到了障碍,因为反转数据的分组不会翻转注释(当然)。但我想翻转一切。
关于如何在不使海洋沸腾的情况下做到这一点的任何想法?
library(tidyverse)
mtcars %>%
mutate( make = word(rownames(mtcars))) %>%
group_by(make) %>%
summarize(wt = sum(wt)) %>%
head ->
mt
p <- ggplot(mt, aes(x = make, y = wt)) +
geom_bar(stat = "identity") +
annotate(
"rect",
xmin = 1.5,
xmax = 4.5,
ymin = 4,
ymax = 7,
alpha = .5
) +
annotate("label", x = 3, y = 6, label = "WTF, y'all?")
p
scale_x_reverse
我发现由于某种原因我什至无法使用:
p + scale_x_reverse()
#> Error in -x: invalid argument to unary operator
请注意,我在此处的可重现示例已大大简化。在实践中,我的图表上有许多不同类型的元素。
解决方案
scale_x_reverse
用于连续缩放。在这里,您将需要使用因子和scale_x_discrete
:
library(tidyverse)
mtcars %>%
mutate( make = word(rownames(mtcars))) %>%
group_by(make) %>%
summarize(wt = sum(wt)) %>%
head %>%
mutate( make = as.factor(make) ) -> # make `make` as a factor
mt
p <- ggplot(mt, aes(x = make, y = wt)) +
geom_bar(stat = "identity") +
annotate(
"rect",
xmin = 1.5,
xmax = 4.5,
ymin = 4,
ymax = 7,
alpha = .5
) +
annotate("label", x = 3, y = 6, label = "WTF, y'all?")
p
# reverse used order of factor levels
p + scale_x_discrete(limits = rev(levels(mt$make)))
推荐阅读
- python - 如何指定 dt.week 在数据框 pandas 中使用北美周数?
- javascript - 如何从 node_modules 导入 JS 库
- javascript - Python selenium如何确认打开whatsapp Web的javascript消息
- vba - 在 Outlook 模板文件 (.oft) 中编辑占位符
- python - VS Code - 在模块模式下为 console_script 运行调试配置
- javascript - 如何通过 Google App Script 获取单元格编辑历史记录?
- java - 如何判断我的 Timer 是否已完成所有任务?
- angular - 如何使用测试数据对@ouput 进行单元测试,Angular 8?
- javascript - 错误 .zip 包含使用 JSZip 的多个 .pdf 文件
- django - 带有附加参数的 Django 自定义模型方法