r - ggplot - 堆叠的 geom_bar - 将每个 x 按 y 重新排序
问题描述
我试图geom_bar
为每个堆叠重新排序,x
但没有成功。我想要实现的是一个图,其中对于 x 的每个值,y 值从最小到最大排序。像这样的东西:
然而,问题似乎是ggplot
威胁 y 作为离散值而不是连续值,因此我无法更改 y 轴的中断和标签。我试过使用scale_x_discrete
没有成功。
library(tidyverse)
df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)),
typ = rep(c("A", "B", "C"), 2),
val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()
ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ))
ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_continuous()
Error: Discrete value supplied to continuous scale
以下代码根本不会改变我的休息时间。
ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_discrete(breaks = 1:10)
解决方案
在@kath 的帮助下,我设法解决了它
library(tidyverse)
df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)),
typ = rep(c("A", "B", "C"), 2),
val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()
bars <- map(unique(df$q)
, ~geom_bar(stat = "identity", position = "stack"
, data = df %>% filter(q == .x)))
df %>%
ggplot(aes(x = q, y = val, fill = reorder(typ,val))) +
bars +
guides(fill=guide_legend("ordering")) +
scale_y_continuous(breaks = 1:10, limits = c(0, 10))
推荐阅读
- machine-learning - 提取属性 Open Vino 时发生意外异常
- jquery - Laravel - 编辑模式表单下拉列表不显示数据
- apache-beam - 延迟数据处理 | 阿帕奇梁
- java - Hashtable 比 HashMap 快?
- php - Xdebug 总是等待 idekey 与 PhpStorm 和 WAMP 服务器的传入连接
- python-3.x - 在传递的变量中渲染 Jinja 标记
- python - 使用列表乘法方法初始化几个空列表将它们链接在一起?
- c# - 有没有办法测试 Singleton 是否被多次实例化
- ruby-on-rails - file_fixture_upload 在 rspec rails 6 中始终将 File 对象作为字符串传递
- angular - RESOLVE Angular 属性“照片”在类型“Spot []”上不存在