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













1















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?










share|improve this question




























    1















    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?










    share|improve this question


























      1












      1








      1








      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 23:32









      LocoGris

      2,4001727




      2,4001727










      asked Mar 8 at 22:41









      skipndippskipndipp

      63




      63






















          1 Answer
          1






          active

          oldest

          votes


















          0














          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))


          enter image description here



          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))


          enter image description here






          share|improve this answer























            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
            );



            );













            draft saved

            draft discarded


















            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









            0














            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))


            enter image description here



            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))


            enter image description here






            share|improve this answer



























              0














              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))


              enter image description here



              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))


              enter image description here






              share|improve this answer

























                0












                0








                0







                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))


                enter image description here



                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))


                enter image description here






                share|improve this answer













                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))


                enter image description here



                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))


                enter image description here







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 9 at 5:31









                wwwwww

                28.6k112345




                28.6k112345





























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme