How to fill in ggplot shapefile map using a variable?How to make a great R reproducible exampleChange order of drawing geom_polygon, ggplotHow can we make xkcd style graphs?R help: mapping - interpolate and contoursUsing ggplot to plot a map from a matrixHow can I use different color or linetype aesthetics in same plot with ggplot?How to create a choropleth map of Europe with ggplotHow do I add state and county lines to a geom_raster ggplot in R?Adding density to a spatial map in RTrouble Creating Map (ggplot) and Shading by Attribute
Can compressed videos be decoded back to their uncompresed original format?
How do conventional missiles fly?
Size of subfigure fitting its content (tikzpicture)
Is it inappropriate for a student to attend their mentor's dissertation defense?
How to Recreate this in LaTeX? (Unsure What the Notation is Called)
One verb to replace 'be a member of' a club
What do you call someone who asks many questions?
Detention in 1997
Unlock My Phone! February 2018
How do I gain back my faith in my PhD degree?
Is there an expression that means doing something right before you will need it rather than doing it in case you might need it?
Can my sorcerer use a spellbook only to collect spells and scribe scrolls, not cast?
How could indestructible materials be used in power generation?
What reasons are there for a Capitalist to oppose a 100% inheritance tax?
Why is this clock signal connected to a capacitor to gnd?
Can we compute the area of a quadrilateral with one right angle when we only know the lengths of any three sides?
Should I cover my bicycle overnight while bikepacking?
Short story with a alien planet, government officials must wear exploding medallions
Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?
All in one piece, we mend holes in your socks
Is it possible to create a QR code using text?
Avoiding the "not like other girls" trope?
How much of data wrangling is a data scientist's job?
How badly should I try to prevent a user from XSSing themselves?
How to fill in ggplot shapefile map using a variable?
How to make a great R reproducible exampleChange order of drawing geom_polygon, ggplotHow can we make xkcd style graphs?R help: mapping - interpolate and contoursUsing ggplot to plot a map from a matrixHow can I use different color or linetype aesthetics in same plot with ggplot?How to create a choropleth map of Europe with ggplotHow do I add state and county lines to a geom_raster ggplot in R?Adding density to a spatial map in RTrouble Creating Map (ggplot) and Shading by Attribute
I am trying to fill a US map where each state is filled in by mean salary (In the default colour scale). I have the shapefile, and a dataframe which looks like this (Data falsified):
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
Here is my code:
library(tidyverse)
library(rgdal)
map <- readOGR(dsn = ".", layer = "usamap")
PlotData <- merge(map, data, by = "State")
This all works so far. I can also make an empty map:
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = NA)
map_base
However, I can't fill in the map with the values.
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = PlotData$MeanSalary)
map_base
I get this error:
Error: Aesthetics must be either length 1 or the same as the data (2834334): fill
What am I getting wrong?
r ggplot2 shapefile
add a comment |
I am trying to fill a US map where each state is filled in by mean salary (In the default colour scale). I have the shapefile, and a dataframe which looks like this (Data falsified):
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
Here is my code:
library(tidyverse)
library(rgdal)
map <- readOGR(dsn = ".", layer = "usamap")
PlotData <- merge(map, data, by = "State")
This all works so far. I can also make an empty map:
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = NA)
map_base
However, I can't fill in the map with the values.
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = PlotData$MeanSalary)
map_base
I get this error:
Error: Aesthetics must be either length 1 or the same as the data (2834334): fill
What am I getting wrong?
r ggplot2 shapefile
add a comment |
I am trying to fill a US map where each state is filled in by mean salary (In the default colour scale). I have the shapefile, and a dataframe which looks like this (Data falsified):
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
Here is my code:
library(tidyverse)
library(rgdal)
map <- readOGR(dsn = ".", layer = "usamap")
PlotData <- merge(map, data, by = "State")
This all works so far. I can also make an empty map:
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = NA)
map_base
However, I can't fill in the map with the values.
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = PlotData$MeanSalary)
map_base
I get this error:
Error: Aesthetics must be either length 1 or the same as the data (2834334): fill
What am I getting wrong?
r ggplot2 shapefile
I am trying to fill a US map where each state is filled in by mean salary (In the default colour scale). I have the shapefile, and a dataframe which looks like this (Data falsified):
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
Here is my code:
library(tidyverse)
library(rgdal)
map <- readOGR(dsn = ".", layer = "usamap")
PlotData <- merge(map, data, by = "State")
This all works so far. I can also make an empty map:
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = NA)
map_base
However, I can't fill in the map with the values.
map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = PlotData$MeanSalary)
map_base
I get this error:
Error: Aesthetics must be either length 1 or the same as the data (2834334): fill
What am I getting wrong?
r ggplot2 shapefile
r ggplot2 shapefile
edited Mar 8 at 23:32
LocoGris
2,4001727
2,4001727
asked Mar 8 at 22:41
skipndippskipndipp
63
63
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Here I provided two solutions to plot polygons using ggplot2
.
Solution 1: geom_sf
sf
class is the next generation spatial data class in R. geom_sf
can plot the sf
object. To do this, we need to convert the sp
object to sf
object. Here I used the state spatial polygons from the USAboundaries
package as an example.
library(tidyverse)
library(sf)
library(USAboundaries)
# Get the state data
state <- us_states()
# Check the class
class(state)
# [1] "sf" "data.frame"
# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))
# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))
Solution 2: ggspatial package
The ggspatial package
can plot the sp
object. So if you don't want to work with sf
object, using ggspatial
could be an option.
library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)
# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")
# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071999%2fhow-to-fill-in-ggplot-shapefile-map-using-a-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here I provided two solutions to plot polygons using ggplot2
.
Solution 1: geom_sf
sf
class is the next generation spatial data class in R. geom_sf
can plot the sf
object. To do this, we need to convert the sp
object to sf
object. Here I used the state spatial polygons from the USAboundaries
package as an example.
library(tidyverse)
library(sf)
library(USAboundaries)
# Get the state data
state <- us_states()
# Check the class
class(state)
# [1] "sf" "data.frame"
# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))
# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))
Solution 2: ggspatial package
The ggspatial package
can plot the sp
object. So if you don't want to work with sf
object, using ggspatial
could be an option.
library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)
# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")
# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))
add a comment |
Here I provided two solutions to plot polygons using ggplot2
.
Solution 1: geom_sf
sf
class is the next generation spatial data class in R. geom_sf
can plot the sf
object. To do this, we need to convert the sp
object to sf
object. Here I used the state spatial polygons from the USAboundaries
package as an example.
library(tidyverse)
library(sf)
library(USAboundaries)
# Get the state data
state <- us_states()
# Check the class
class(state)
# [1] "sf" "data.frame"
# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))
# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))
Solution 2: ggspatial package
The ggspatial package
can plot the sp
object. So if you don't want to work with sf
object, using ggspatial
could be an option.
library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)
# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")
# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))
add a comment |
Here I provided two solutions to plot polygons using ggplot2
.
Solution 1: geom_sf
sf
class is the next generation spatial data class in R. geom_sf
can plot the sf
object. To do this, we need to convert the sp
object to sf
object. Here I used the state spatial polygons from the USAboundaries
package as an example.
library(tidyverse)
library(sf)
library(USAboundaries)
# Get the state data
state <- us_states()
# Check the class
class(state)
# [1] "sf" "data.frame"
# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))
# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))
Solution 2: ggspatial package
The ggspatial package
can plot the sp
object. So if you don't want to work with sf
object, using ggspatial
could be an option.
library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)
# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")
# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))
Here I provided two solutions to plot polygons using ggplot2
.
Solution 1: geom_sf
sf
class is the next generation spatial data class in R. geom_sf
can plot the sf
object. To do this, we need to convert the sp
object to sf
object. Here I used the state spatial polygons from the USAboundaries
package as an example.
library(tidyverse)
library(sf)
library(USAboundaries)
# Get the state data
state <- us_states()
# Check the class
class(state)
# [1] "sf" "data.frame"
# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")
# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))
# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))
Solution 2: ggspatial package
The ggspatial package
can plot the sp
object. So if you don't want to work with sf
object, using ggspatial
could be an option.
library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)
# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")
# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))
answered Mar 9 at 5:31
wwwwww
28.6k112345
28.6k112345
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071999%2fhow-to-fill-in-ggplot-shapefile-map-using-a-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown