【问题标题】:R : Fill in / map / plot a Shapefile with ggplot2, based on the values of a regoinR :根据 regoin 的值,使用 ggplot2 填充/映射/绘制 Shapefile
【发布时间】:2016-07-26 00:00:36
【问题描述】:

最好的

我有以下 shapefile,它是法兰德斯(比利时)的地图,我想用 ggplot 相对于 cheapestEnergyPrices 绘制它。 (因此使用渐变色)

head(flanders@data, n = 1)
  OBJECTID  Cs012011      Nis_   ...  Sec    Commune     Prov_nl    Reg_nl       cheapestEnergyPrices   mostExpensiveEnergyprices
  3         11001A00-     11001  ...  A00-   AARTSELAAR  Antwerpen  Vlaanderen   935.03                 1254.74


head(flanders@polygons, n=1)
[[1]]
An object of class "Polygons"
Slot "Polygons":
[[1]]
An object of class "Polygon"
Slot "labpt":
[1]  4.387485 51.132957

Slot "area":
[1] 6.825956e-05

Slot "hole":
[1] FALSE

Slot "ringDir":
[1] 1

Slot "coords":
           [,1]     [,2]
  [1,] 4.385794 51.13767
  [2,] 4.386132 51.13745
  ...  ...      ...
[147,] 4.385794 51.13767



Slot "plotOrder":
[1] 1

Slot "labpt":
[1]  4.387485 51.132957

Slot "ID":
[1] "0"

Slot "area":
[1] 6.825956e-05

此时我已经尝试了很多东西,例如下一段代码:

> ggplot() + geom_polygon(data = flanders, aes(x = long, y = lat, group = group,fill = flanders$cheapestEnergyPrices))

但不幸的是它会给我下一个错误代码

Regions defined for each Polygons
Error: Aesthetics must be either length 1 or the same as the data (1224957): x, y, group, fill

然而,当我将 flanders$cheapestEnergyPrices 替换为 1 时,例如:

ggplot() + geom_polygon(data = flanders, aes(x = long, y = lat, group = group,fill = 1))

然后我会得到这个不需要的结果,因为所有东西都包含相同的颜色。

因此...我想用 ggplot2 绘制我的 shapefile,其中多边形被着色,例如最便宜的能源价格。 例如,cheapestEnergyPrice 最低的 commune 将具有深绿色,而 cheapestEnergyPricecommune 则要高得多会有浅绿色/白色,甚至是红色......

【问题讨论】:

  • cheapestEnergyPrices 定义为factor 会改变它吗?
  • 这似乎是个错误:geom_polygon(data = flanders, aes(..., fill = flanders$cheapestEnergyPrices))。因为它在aes 内部,所以你应该只传递fill = cheapestEnergyPrices,并去掉flanders$ 前缀
  • ...但很难进一步提供帮助,因为如果没有 shapefile,情节无法从您发布的内容中重现

标签: r ggplot2 shapefile


【解决方案1】:

也许:

ggplot() + geom_polygon(data = flanders, aes(x = long, y = lat, group = group, fill = cheapestEnergyPrices))

我认为您不需要重新传递flanders$,但如果没有您的数据很难判断。由于您的列似乎是数字,因此色标应遵循。

我猜flandersfortify-由ggplot 即时编辑并变成data.frame。一个更简单的选择是:

i) 使用 fortifyeven better broom::tidyflanders 转换为 data.frame

ii) 将此data.frameggplot2 一起使用,以及其他数据操作。

类似:

flanders_df <- broom::tidy(flanders)
ggplot() + geom_polygon(data = flanders_df, aes(x = long, y = lat, group = group, fill = cheapestEnergyPrices))

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2022-08-14
    • 2021-11-13
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多