structure(list(Date = structure(c(1372698000, 1291129200, 1291388400,
1298646000, 1386007200, 1295017200, 1382104800, 1385240400, 1265986800,
1364835600), class = c("POSIXct", "POSIXt"), tzone = ""), Logons = c(" 973,675",
" 710,782", " 734,635", " 812,793", "1,126,432", " 916,832",
"1,011,911", "1,974,513", " 674,884", "1,278,295"), Month = structure(c(7L,
11L, 12L, 2L, 12L, 1L, 10L, 11L, 2L, 4L), .Label = c("January",
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"), class = "factor"),
Max = c(973675L, 710782L, 734635L, 812793L, 1126432L, 916832L,
1011911L, 1974513L, 674884L, 1278295L), Year = c("2013",
"2010", "2010", "2011", "2013", "2011", "2013", "2013", "2010",
"2013")), .Names = c("Date", "Logons", "Month", "Max", "Year"
), row.names = c(453L, 2564L, 2636L, 3343L, 3435L, 4545L, 5275L,
5786L, 7382L, 8077L), class = "data.frame")
我正在尝试创建一个热图,其中Year将在y轴上,而Month将在x轴上。
我这样做:
ggplot(y ,aes(Month, Year, fill=Logons, label=paste(paste(weekdays(Date), format(Date,"%H:%M"), sep="\n"), "\n",Logons))) + geom_tile() + theme_bw() + guides(fill = guide_legend(keywidth = 5, keyheight = 1)) + theme(axis.text.x = element_text(size=10, angle=45, hjust=1)) + geom_text(size=3)+ scale_colour_manual(breaks = c(200000, 400000, 800000, 1000000, 1300000, 1500000), labels = c("0 month", "1 month", "3 months","6 months", "9 months", "12 months"),values = c("#E69F00", "#56B4E9", "#009E73","#F0E442", "#0072B2", "#D55E00"))
不工作。我的传奇中有很多项目,我的热图中只需要6个项目和6个颜色代码。任何想法为什么这不起作用?
答案 0 :(得分:2)
您数据中的第一个问题是Logons
被视为因素,而不是数字,因为数字中有逗号。所以你必须将它们转换为数字。
y$Logons<-as.numeric(gsub(",","",y$Logons))
由于fill=
使用了geom_tile()
,因此您必须使用scale_fill_...
来更改填充值。在这种情况下,请使用scale_fill_gradientn()
来设置填充值的格式。
ggplot(y ,aes(Month, Year, fill=Logons,
label=paste(paste(weekdays(Date), format(Date,"%H:%M"), sep="\n"), "\n",Logons))) +
geom_tile() + theme_bw() +
guides(fill = guide_legend(keywidth = 5, keyheight = 1)) +
theme(axis.text.x = element_text(size=10, angle=45, hjust=1)) +
geom_text(size=3)+
scale_fill_gradientn(limits=c(200000, 1500000),
breaks = c(200000, 400000, 800000, 1000000, 1300000, 1500000),
labels = c("0 month", "1 month", "3 months","6 months", "9 months", "12 months"),
colours = c("#E69F00", "#56B4E9", "#009E73","#F0E442", "#0072B2", "#D55E00"))
此外,我认为您应该从代码中删除guides(fill = guide_legend(keywidth = 5, keyheight = 1))
行,因为填充颜色会更改为渐变,但现在您在图例中获得的离散值与图中的颜色不完全匹配。