标签乱序(ggplot2)
Labels are out of order (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)
剧情:
当我为绘图添加标签时,它们的顺序错误。我想重新排列标签,而不是条形图本身。示例代码:
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)
剧情: