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。得到它了。謝謝! –
我將不得不調查爲什麼這個標記是重複的。在發佈之前,我查看了提到的解決方案。它看起來很近,但沒有幫助我看到我需要理解的東西。我認爲格里高爾的回答幫助我實現了我目前知識水平的目標...... –