1
我要求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))
您的代码使用的唯一软件包是'ggplot2'和'tidyr'(已编辑)。在将来,不要使用“dput(df)'...将df转换为x的代码......关于如何绘制”x“的问题,只需要'dput(x)',因为转换是无关紧要的。 – Gregor
Gregor。得到它了。谢谢! –
我将不得不调查为什么这个标记是重复的。在发布之前,我查看了提到的解决方案。它看起来很近,但没有帮助我看到我需要理解的东西。我认为格里高尔的回答帮助我实现了我目前知识水平的目标...... –