我的情节有两个问题:
(1)组栏的排列顺序不符合我的要求-我希望它们按输入的顺序显示,(2)图例,顺序显示为 V,E,B < / strong>,而在组中则显示为 B,E,V 。我可以改变传说,但是,我真正想要得到的是将子图的顺序更改为 V,E,B 。
library(ggplot2)
df2 <- data.frame(supp = rep(c("V","E","B"), each=5),
s = rep(c("C3","C1", "C2","C5","C6"), 3),
len = c(1,2,3,4,5,6,8,4,4,3,9,7,6,8,5))
p <- ggplot(data = df2, aes(x = s, y = len, fill = supp)) +
geom_bar(stat = "identity", color = "black", position = position_dodge())
p + scale_fill_brewer(palette = "Blues", guide = guide_legend(reverse = TRUE)) +
scale_x_discrete(limits = rev(levels(df2$s)))
答案 0 :(得分:2)
您需要将df2$supp
从字符更改为因数,并根据需要显示它们来指定级别。
请参阅下面的修改后的代码。另外,请查看this link,以获取有关如何控制变量颜色以使其一致的更多详细信息。
library(ggplot2)
df2 <- data.frame(supp = rep(c("V","E","B"), each=5),
s = rep(c("C3","C1", "C2","C5","C6"), 3),
len = c(1,2,3,4,5,6,8,4,4,3,9,7,6,8,5))
df2$supp <- factor(df2$supp,
levels = c("V", "E", "B"))
p <- ggplot(data=df2, aes(x=(df2$s), y=len, fill=supp)) +
geom_bar(stat="identity", color="black", position=position_dodge())
p + scale_fill_brewer(palette="Blues", guide = guide_legend(reverse=TRUE)) +
scale_x_discrete(limits = rev(levels(df2$s)))
答案 1 :(得分:1)
数据
df2 <- data.frame(supp = rep(c("V", "E", "B"), each = 5),
s = rep(c("C3", "C1", "C2", "C5", "C6"), 3),
len = c(1, 2, 3, 4, 5, 6, 8, 4, 4, 3, 9, 7, 6, 8, 5))
调整
由于使用data.frame()
创建数据,因此R默认情况下会将字符串设置为因子。因此,您需要将变量类型修改为所需的变量。
df2$s <- as.character(df2$s)
df2$supp <- factor(df2$supp, levels = c("V", "E", "B"))
情节
ggplot(data = df2, aes(x = s, y = len, fill = supp)) +
geom_bar(stat = "identity", color = "black", position = position_dodge()) +
scale_fill_brewer(palette = "Blues", direction = -1)
在这里,你不需要使用额外的guide_legend()
和scale_x_discrete()
改变顺序。会更加简洁。