我通过为特定颜色指定值来创建自己的色阶,如下所示:(Dataframe = df_avg,values column = pmplot,color column = gr_colour)
df_avg$gr_colour[df_avg$pmplot<5] <- "palegreen4"
df_avg$gr_colour[df_avg$pmplot>=5 & df_avg$pmplot<10] <- "palegreen3"
df_avg$gr_colour[df_avg$pmplot>=10 & df_avg$pmplot<12] <- "palegreen2"
df_avg$gr_colour[df_avg$pmplot>=12 & df_avg$pmplot<14] <- "palegreen1"
df_avg$gr_colour[df_avg$pmplot>=14 & df_avg$pmplot<16] <- "lightgoldenrod1"
df_avg$gr_colour[df_avg$pmplot>=16 & df_avg$pmplot<18] <- "khaki1"
df_avg$gr_colour[df_avg$pmplot>=18 & df_avg$pmplot<20] <- "goldenrod1"
df_avg$gr_colour[df_avg$pmplot>=20 & df_avg$pmplot<22] <- "darkgoldenrod1"
df_avg$gr_colour[df_avg$pmplot>=22 & df_avg$pmplot<24] <- "darkorange1"
df_avg$gr_colour[df_avg$pmplot>=24 & df_avg$pmplot<26] <- "darkorange2"
df_avg$gr_colour[df_avg$pmplot>=26 & df_avg$pmplot<28] <- "orangered1"
df_avg$gr_colour[df_avg$pmplot>=28 & df_avg$pmplot<30] <- "orangered3"
df_avg$gr_colour[df_avg$pmplot>=30] <- "red3"
每个PM_value都有一个相应的纬度和经度值,我想将其绘制为沿ggmap的点。我的数据帧的开头如下所示:
Lat Long PM_value colour
-33.92426 151.2280 19.6 goldenrod1
-33.92406 151.2278 16.8 khaki1
-33.92386 151.2278 13.1 palegreen1
我目前正在如下绘制此地图:
map = get_map(location = c(lon = 151.22528, lat = -33.91413), zoom = 15, maptype = "roadmap")
ggmap(map) + geom_point(data = df_avg, aes(x = df_avg$Long, y = df_avg$Lat), col = df_avg$gr_colour, cex = 4)
我想创建一个颜色条,其图例对应于PM_values,颜色条对应于匹配的颜色(在“颜色”列中)。
到目前为止,我已经创建了一个渐变颜色,如下所示:
colfunc <- colorRampPalette(c("palegreen4", "palegreen3", "palegreen2", "palegreen1", "lightgoldenrod1","khaki1", "goldenrod1", "darkgoldenrod1", "darkorange1", "darkorange2", "orangered1", "orangered3"))
plot(rep(1,100),col=colfunc(100),pch=15,cex=3)
如何在此ggmap中创建颜色条以使颜色与“PM_value”中的相应值匹配?
答案 0 :(得分:0)
你可以尝试一下吗?
library(tidyverse)
pal <- c("palegreen4", "palegreen3", "palegreen2", "palegreen1", "lightgoldenrod1","khaki1", "goldenrod1", "darkgoldenrod1", "darkorange1", "darkorange2", "orangered1", "orangered3","red3")
Breaks <- c(0,5,seq(10,30,2))
set.seed(123)
tibble(PM_value=sample(1:50, 500, T)) %>%
mutate(col=cut(PM_value, breaks = c(0,5,seq(10,30,2), max(PM_value)), labels = c(0,5,seq(10,30,2)))) %>%
mutate(col=as.numeric(as.character(col))) %>%
ggplot(aes(x=seq_along(PM_value),y=PM_value, color=col)) +
geom_point() +
scale_colour_gradientn(colors = pal, values=scales::rescale(c(0,5,seq(10,30,2))))