ggplot

时间:2016-02-24 02:40:56

标签: r ggplot2

我想在世界地图上连续填充某些值(压力)作为渐变填充,我正在编写以下代码:

df = data.frame(phi)
names(df) = lat
df$lon= lon
mdata = melt(df, id=c("lon"))
names(mdata) = c("lon", "lat", "x")
mdata$x = as.numeric(mdata$x)
mdata$lon = as.numeric(mdata$lon)
mdata$lat = as.numeric(as.character(mdata$lat))

wr <- map_data("world")
# Prepare a map of World
wrmap <- ggplot(wr, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", colour = "black") +
  geom_point(data=mdata, inherit.aes=FALSE, aes(x=lon, y=lat, colour=x), size=3, shape=4) +
  scale_fill_gradient("Phi", limits=c(4500,6000)) +
  theme_bw() +
  coord_equal()

wrmap

不幸的是,这些要点很谨慎。

enter image description here

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我不确定你想要什么,因为你没有给我们任何数据,但我做了一些猜测并做了这个:

library(ggplot2)
library(maps)
library(reshape2)

# Generate some fake data
lat <- seq(-90, 90, by = 5)
lon <- seq(-180, 180, by = 10)
phi <- 1500*tcrossprod( sin( pi*lat/180 ), cos( pi*lon/180 ))^ 2 + 4500

# above thanks to @NBAtrends for turning my two ugly for loops into this elegant statement

df = data.frame(phi)
names(df) = lat
df$lon = lon
mdata = melt(df, id = c("lon"))
names(mdata) = c("lon", "lat", "x")
mdata$x = as.numeric(mdata$x)
mdata$lon = as.numeric(mdata$lon)
mdata$lat = as.numeric(as.character(mdata$lat))

wr <- map_data("world")
# Prepare a map of World
wrmap <- ggplot(wr, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", colour = "black") +
  geom_point(data=mdata, inherit.aes=FALSE,aes(x=lon, y=lat, color=x),size=3) +
  scale_color_gradient("Phi", limits = c(4500, 6000)) +
  theme_bw() + 
  coord_equal()

wrmap

产生这个,这似乎接近你可能想要的:

enter image description here

这使我得出结论,问题出在您的数据上。通过将它与我的假数据进行比较,我认为你可以找出你的问题。

此外,我将“x”更改为圆形,因为您无法很好地看到它的颜色。