如何基于ggplot中数字列的值为绘制的点分配颜色渐变

时间:2019-12-24 18:58:28

标签: r ggplot2 colors

我有一个很大的数据框,上面有很多观察结果。数据帧称为totdets_per_month,数据的第一行如下所示:

  month yearcollected deploy_long deploy_lat total
  <ord>         <int>       <dbl>      <dbl> <int>
1 Jan            2016       -54.6       39.9     1
2 Jan            2016       -54.6       39.9     2
3 Jan            2016       -54.6       39.9     9
4 Jan            2016       -54.4       39.9     9
5 Jan            2016       -54.4       39.9     2
6 Jan            2016       -54.4       39.9     2

我拥有所有月份在一系列坐标范围内的数据,

我正在尝试将这些坐标映射为点,但是根据我的数字列total将点分配给颜色渐变。

这是我绘制数据框的代码

#Importing a map
world = ne_countries(scale = "medium", returnclass = "sf")


#map of total detections in each zone per month
ggplot(data = world) +
  geom_sf(fill = "lightgrey") +
  coord_sf(xlim=c(-64.5,-62.8), ylim=c(42.7,45), expand = FALSE) +
  geom_rect(data = rect1, aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2), fill = NA, color = "black", size = 1) +
  geom_point(data = totdets_per_month ,
             mapping = aes(x = deploy_long, 
                           y = deploy_lat,
                           fill = total),
             pch = 21) +
  scale_colour_gradient(low="black", high="green") + 
  theme(panel.background = element_rect(fill = "#add8e6"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank()) +
  facet_wrap(vars(month))

这是代码输出的图像 enter image description here

如您所见,这些点都是一种颜色。有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是基于我上面的评论的综合答案:

请注意,色阶从黑色变为蓝色,而不是绿色。您的aes定义有问题。在您的aes中,您要指定“ fill = total”,但您仅定义scale_colour_gradient,首先将scale_colour_gradient更改为scale_fill_gradient

#create sample data
x<- runif(20, 1, 20)
y<-x^4
df<-data.frame(x, y)

library(ggplot2)
#this is a linear scale for the colors
ggplot(df) + geom_point(aes(x=x, y=y, fill=y), pch=21, size=4) +
  scale_fill_gradient(low="black", high="green")

enter image description here

在上面的图中,y的几个极大值导致大多数剩余点都绘制成黑色。为了对此色标进行调整,那么您将需要手动指定颜色中断。 在下面的示例中,我使用cut函数将范围除以10的幂,并将break分配给其他颜色值。

#create color ramp
colfunc <-colorRampPalette(c("black", "green"))

#adjust scaling of the colors and 
#  add custom color color to dataframe
df$color<-cut(y, breaks=c(0, 10, 100, 1000, 10000, 100000, Inf))
df$color<-factor(df$color, labels=colfunc(5))

ggplot(df) + geom_point(aes(x=x, y=y, fill=color), pch=21, size=4) +
  scale_fill_identity(guide="legend", labels=c(10^(1:5)))

enter image description here

现在该图可以更好地显示分布。