我要求R制作一系列情节。但是,ggplot2分配给不同变量的颜色会因实际数据而异。我需要更多的一致性特别是我想:
四是红色 三是绿色 两个是黄色的 一个是白色的
根据以前的答案,我怀疑我需要订购等级。有人可以帮助我吗?
以下是一些示例数据:
df<-structure(list(`id` = structure(c(3L, 3L, 3L, 3L, 3L, 2L,
3L, 3L, 1L, 3L, 4L, 3L, 3L, 3L, 3L, 3L, 2L, 4L, 3L, 3L, 2L, 3L,
2L, 4L, 2L, 4L, 3L, 3L, 2L, 3L, 4L, 3L, 3L, 2L, 3L, 3L, 4L, 3L,
1L, 3L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("ONE",
"TWO", "THREE", "FOUR"), class = "factor"), NAME = c("0", "0.25", "0.5",
"0.75", "1", "1.25", "1.5", "1.75", "2", "2.25", "2.5", "2.75",
"3", "3.25", "3.5", "3.75", "4", "4.25", "4.5", "4.75", "5",
"5.25", "5.5", "5.75", "6", "6.25", "6.5", "6.75", "7", "7.25",
"7.5", "7.75", "8", "8.25", "8.5", "8.75", "9", "9.25", "9.5",
"9.75", "10", "10.25", "10.5", "10.75", "11", "11.25", "11.5",
"11.75", "12", "12.25")), .Names = c("id", "NAME"), row.names = c("0",
"0.25", "0.5", "0.75", "1", "1.25", "1.5", "1.75", "2", "2.25",
"2.5", "2.75", "3", "3.25", "3.5", "3.75", "4", "4.25", "4.5",
"4.75", "5", "5.25", "5.5", "5.75", "6", "6.25", "6.5", "6.75",
"7", "7.25", "7.5", "7.75", "8", "8.25", "8.5", "8.75", "9",
"9.25", "9.5", "9.75", "10", "10.25", "10.5", "10.75", "11",
"11.25", "11.5", "11.75", "12", "12.25"), class = c("tbl_df",
"tbl", "data.frame"))
以下是代码:
library(ggplot2)
library(tidyr)
colors <- c("red","white","yellow","green")
df$NAME <- rownames(df)
x<-gather(df,NAME)
colnames(x)<-c("Name", "variable","value")
ggplot(x,
aes(x = Name, y = variable, fill = factor(value))) +
geom_tile() +
scale_fill_manual(values=colors)+
scale_x_discrete(name="Time Period", limits= rownames(df))
答案 0 :(得分:5)
正如您所说,您需要指定因子级别的顺序:
x$value = factor(x$value, levels = c("ONE", "TWO", "THREE", "FOUR"))
# the order of the vector you pass to levels defines the order of the factor
然后您需要以相同的顺序定义颜色向量。
# "FOUR to be red THREE to be green TWO to be yellow ONE to be white"
colors <- c("white","yellow","green","red")
另一种方法是命名颜色矢量(下图),但我更喜欢第一种方式。
colors <- c("red","white","yellow","green")
names(colors) = c("FOUR", "ONE", "TWO", "THREE")
colors
# FOUR ONE TWO THREE
# "red" "white" "yellow" "green"
无论哪种方式,您的绘图代码都可以正常工作。