r - 标签乱序(ggplot2)
问题描述
当我在情节中添加标签时,它们的顺序错误。我想重新排列标签,而不是条形本身。示例代码:
df = data.frame(A = c("Apples", "Apples", "Apples", "Apples", "Apples", "Apples",
"Oranges", "Oranges", "Oranges", "Oranges", "Oranges", "Oranges"),
B = c("Red", "Green", "Red", "Green", "Red", "Green",
"Red", "Green", "Red", "Green", "Red", "Green"),
C = c(3, 4, 2, 3, 4, 6, 2, 2, 3, 8, 8, 6))
library(tidyverse)
df.summary = df %>%
group_by(A, B) %>%
summarise(new = list(mean_se(C))) %>%
unnest(new)
df.summary$B <- factor(df.summary$B, levels = c("Red", "Green"))
df.labels = c(1, 2, 3, 4)
ggplot(df.summary, aes(x = A, y = y, fill = factor(B))) +
geom_bar(stat = "identity", position = position_dodge(.95)) +
geom_errorbar(aes(ymin = ymin, ymax = ymax, width = 0.5),
position = position_dodge(.95)) +
geom_text(position = position_dodge(width = 1), size = 6,
label = df.labels, hjust = .5, vjust = 0, angle = 0)
我们得到:
标签顺序不正确的条形图(2-1-4-3 而不是 1-2-3-4):
以不同方式重构数据不会改变标签。无论我尝试什么,我都无法按正确的顺序排列它们。我假设这是一个问题,geom_text
但我一生都无法弄清楚。
这是怎么回事?
解决方案
这有帮助吗?假定(假设?)A 和 B 是因子。
library(tidyverse)
df.summary$A<-fct_reorder(df.summary$A,df.labels)
df.summary$B<-fct_reorder(df.summary$B,df.labels)
ggplot(df.summary, aes(x=A, y=y, fill=B))+
geom_bar(stat = "identity", position = position_dodge(.95))+
geom_errorbar(aes(ymin=ymin, ymax=ymax, width=0.5), position=position_dodge(.95))+
geom_text(position = position_dodge(width = 1), size = 6, aes(label = df.labels),
hjust = .5, vjust = 0, angle = 0)
推荐阅读
- java - 循环遍历两个不同的数组java
- arm-template - 用于在 Log Analytics 中创建警报规则的 ARM 模板
- javascript - 角柱可见性
- android - 如果我使用私人 sim 互联网而不连接全球互联网,那么在移动应用程序中我需要做什么设置?
- apache - Apache EC2 安装 ssl 证书
- google-bigquery - 将数据从 FCM/Firebase 流式传输到 BigQuery
- jquery - 面对未捕获的类型错误:无法在 jquery.event.drag-2.2.js:383 控制台中设置未定义的属性“touchcancel”
- c# - 时间:2019-05-10 标签:c#webform enable gridview edit delete,根本不使用sql
- swiftui - 如何在 SwiftUI 中从父视图更改子 @State 属性值?
- android - Flutter Geolocator 和 Google Maps:显示静态位置