如何在图例中显示样本大小?

时间:2014-08-01 20:56:08

标签: r ggplot2

我有这个代码。我有我想要的数字。但我还想将样本大小放在标签旁边。例如,在92-94之间的90-92,500点之间可能有100个点,我想在标签旁边或图中的某个位置显示这些数字。你能帮忙吗?

makeQuantiles <- function(x, probs = seq(0.9, 1, by = 0.02)) {
  cut(x, breaks = qu <- quantile(x, probs = probs),
      labels = names(qu)[-1], include.lowest = TRUE)
}
foo1$quantile<-makeQuantiles(foo1$mnqtp)
ggplot() + 
  geom_polygon( data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white" )+
  geom_point(data=na.omit(foo1),aes(x=lon,y=lat,color=quantile))+
  coord_map(projection = "mercator")+
  theme_bw()+
  theme(legend.position = c(.93,.20),panel.grid.major = element_line(colour = "#808080"))

enter image description here

1 个答案:

答案 0 :(得分:3)

基本想法是将计数添加到cut(...)

中的标签
set.seed(1)    # for reproducible example
N <- 1000
df <- data.frame(lon = sample(-125:-65,N,replace=T), 
                 lat = sample(25:50,N,replace=T),
                 mqntp=sample(1:N,N,replace=T))

# you start here...
makeQuantiles <- function(x, probs = seq(0.9, 1, by = 0.02)) {
  qu <- quantile(x, probs=probs)
  br <- cut(x, breaks = qu, labels = names(qu)[-1], 
            include.lowest = TRUE)
  ct <- table(br)
  cut(x, breaks = qu, labels = paste0(names(qu)[-1]," (",ct,")"), 
      include.lowest = TRUE)
}
df$quantile <- makeQuantiles(df$mqntp)
library(ggplot2)
ggplot(na.omit(df), aes(x=lon,y=lat,color=quantile))+geom_point()