Dieter
Dieter

Reputation: 2659

R : Fill in / map / plot a Shapefile with ggplot2, based on the values of a regoin

Best

I've the following shapefile which is a map of Flanders (Belgium), and I would like to plot it with ggplot with respect to the cheapestEnergyPrices. (thus use a gradient colour)

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

At this point I've tried a lot of things, like e.g. the next piece of code :

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

But unfortunately it will give me the next error code

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

Yet, when I replace flanders$cheapestEnergyPrices by 1, like :

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

then I will get this unwanted result, because everything contains the same colour.

enter image description here

Thus ... I would like to plot my shapefile with ggplot2, whereby the polygones are coloured in, with respect to the value of e.g. cheapestEnergyPrices. For example the commune which cheapestEnergyPrice is the lowest would have a DarkGreen colour and a commune who's cheapestEnergyPrice is much higher would have a light green / white, or even a red colour...

Upvotes: 1

Views: 1620

Answers (1)

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7453

Perhaps:

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

I think you do not neet to repass flanders$ but it's hard to tell without your data. As your column seems to be a numeric, the colour scale should follow.

I guess flanders is fortify-ed on the fly by ggplot and turned into a data.frame. A simpler alternative would be to:

i) turn flanders into a data.frame with fortify or even better broom::tidy

ii) use this data.frame with ggplot2, and other data manipulation.

Something like:

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

Upvotes: 1

Related Questions