2017-09-04 26 views
1

我正在开发一个模拟失踪船只移动的项目。显示图形中每点的计数(统计)

library("ggplot2") 

a <- rnorm(1000, 30.2, 2) 
b <- rnorm(1000, 10, 5) 
y <- (x + a + b) * 0.6 

df <- data.frame(x,y) 
p <- ggplot(df,aes(x=x,y=y)) + 
    ggtitle("A Priori Map") + xlab("Longtitude") + ylab("Latitude") + 
    scale_fill_gradientn(colors = topo.colors(10)) 

p + stat_binhex(show.legend = T, bins = 20) 

这将产生一个地图是这样的:我已经使用这个代码做了一个分布图

A hexbin map

然而,而不是出了使用颜色数的数量,我想以显示一个点的实际计数。所以如果程序“登陆”某个点3次,它会显示'3'。

这怎么能在R中完成?

+0

有没有在您的样本数据中没有'x'。 – eipi10

回答

5

以下是如何计数添加到现有的图形:

library(ggplot2) 
theme_set(theme_bw()) 

set.seed(2) 
a <- rnorm(1000, 30.2, 2) 
b <- rnorm(1000, 10, 5) 
x = rnorm(1000) 
y <- (x + a + b) * 0.6 

df <- data.frame(x,y) 

p <- ggplot(df,aes(x=x,y=y)) + 
    ggtitle("A Priori Map") + 
    xlab("Longtitude") + ylab("Latitude") + 
    scale_fill_gradientn(colors = topo.colors(10)) + 
    stat_binhex(show.legend = T, bins = 20) 

p + geom_text(stat="binhex", bins=20, aes(label=..count..), show.legend=FALSE, 
       colour=hcl(15,100,60), fontface="bold", size=3.5) 

enter image description here

要取出填充颜色,你可以这样做:

ggplot(df,aes(x=x,y=y)) + 
    ggtitle("A Priori Map") + 
    xlab("Longtitude") + ylab("Latitude") + 
    stat_binhex(bins = 20, fill=NA, colour="black") + 
    geom_text(stat="binhex", bins=20, aes(label=..count..), colour="red") 

enter image description here

你可以也使用文字大小来突出显示该区域密度最高的S:

ggplot(df,aes(x=x,y=y)) + 
    ggtitle("A Priori Map") + 
    xlab("Longtitude") + ylab("Latitude") + 
    stat_binhex(show.legend = T, bins = 20, fill=NA, colour="grey70") + 
    geom_text(stat="binhex", bins=20, aes(label=..count.., size=..count..), colour="red") + 
    scale_size_continuous(range=c(3,6)) + 
    guides(size=FALSE) 

enter image description here

这也是作品,未经六角格:

ggplot(df,aes(x=x,y=y)) + 
    ggtitle("A Priori Map") + 
    xlab("Longtitude") + ylab("Latitude") + 
    geom_text(stat="binhex", bins=20, aes(label=..count.., size=..count..), colour="red") + 
    scale_size_continuous(range=c(3,6)) + 
    guides(size=FALSE) 

enter image description here

+0

正是我需要和更多。感谢您的帮助! – RedGreenBlue

+0

如果这符合您的需求,请考虑点击“接受答案”复选标记。 – eipi10