我试图控制绘制因子的顺序,并为它们指定特定的颜色。我对ggplot2
相当新,是最近一次不情愿的基础图形转换。
以下是一个例子:
df <- data.frame(fac = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"),
val = c(10, 4, 7))
ggplot(data = df, aes(x = fac, y = val, fill = fac)) +
geom_bar(stat="identity", width=0.9) +
scale_fill_manual(values=c("blue", "red", "orange")) +
scale_x_discrete(limits = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))
我想要&#34;服从Cowgod&#34;变成蓝色,&#34;三只小猪&#34;变成红色,和#34;谷物杀手&#34;变成橙色怎么办呢?
答案 0 :(得分:2)
您应该将列级别的顺序设置为一个因子。
df$fac <- factor(df$fac, levels = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))
现在颜色将分配给正确的名称。
(编辑注释:正如Gregor在评论中指出的那样,不再需要scale_x_discrete)
完整代码:
df <- data.frame(fac = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"),
val = c(10, 4, 7))
df$fac <- factor(df$fac, levels = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))
ggplot(data = df, aes(x = fac, y = val, fill = fac)) +
geom_bar(stat="identity", width=0.9) +
scale_fill_manual(values=c("blue", "red", "orange"))
输出:
答案 1 :(得分:2)
两种方式:
一个 - 按原样保留数据并使用命名向量进行填充values
:
ggplot(data = df, aes(x = fac, y = val, fill = fac)) +
geom_bar(stat="identity", width=0.9) +
scale_fill_manual(values=c("Obey the Cowgod" = "blue", "Three Little Pigs" = "red", "Cereal Killer" = "orange")) +
scale_x_discrete(limits = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))
两个 - 按照您想要绘制的顺序按要素级别的顺序编辑数据,如Cihan的答案。我更喜欢这个,它是在我写的时候发布的:)
答案 2 :(得分:2)
不要依赖于字符串的自动转换。在提供的代码中,级别以alpha顺序给出。
df <- data.frame(fac = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"),
val = c(10, 4, 7))
levels(df$fac)
# [1] "Cereal Killer" "Obey the Cowgod" "Three Little Pigs"
通过明确地将df$fac
设置为您希望ggplot代码无需更改的级别的因素。
df <- data.frame(fac = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"),
val = c(10, 4, 7),
stringsAsFactors = FALSE)
df$fac <- factor(df$fac, levels = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))
levels(df$fac)
# [1] "Obey the Cowgod" "Three Little Pigs" "Cereal Killer"
无需更改ggplot代码
library(ggplot2)
ggplot(data = df, aes(x = fac, y = val, fill = fac)) +
geom_bar(stat="identity", width=0.9) +
scale_fill_manual(values=c("blue", "red", "orange")) +
scale_x_discrete(limits = c("Obey the Cowgod", "Three Little Pigs", "Cereal Killer"))