Matplotlib choropleth map plotting two different pieces of data












1














So far I have produced a Choropleth map by:



fig, ax = plt.subplots(1, figsize=(32, 16))
ax.axis('off')

df.plot(column='Income Rank', scheme='quantiles', k=7,legend=True, cmap='YlOrRd_r', ax=ax)
ax.annotate(xy=(0.1, .08), xycoords='figure fraction', horizontalalignment='left', verticalalignment='top'
,s='Income deprivation Rank. Lowest rank = most deprived.')


which looks like this:
enter image description here



My DF Looks like this:



geometry    Counts  WardCode Ward Name   Income Rank                                                                
POLYGON (()) 1545 N09000001 Abbey 3


So it plots the rank of each area in relation to income data I have in df. Is it possible for me to plot crimes on this map aswell? I am trying to show the link between low income and high crime rate.. For example, with markers or maybe use a different colour scheme to represent high crime areas? The dataframe with my crimes looks like this:



WARDNAME    Counts
0 CENTRAL 3206
1 DUNCAIRN 757
2 BLACKSTAFF 584


I also have a df of crimes that have Latitude and Longitude, that looks like this:



Crime ID    Date    Longit  Latit   Crime type  Ward Name   Ward Code
0 01 2016-01 -5.886699 54.591309 Theft CENTRAL N08000313


Is the only way I can plot both of these things on the same map by using Folium and plotting the Choropleth with the income values and then plotting the crimes as markers? Or can I do it without folium?
Thanks










share|improve this question
























  • Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
    – user32185
    Nov 20 '18 at 13:14










  • @user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
    – Liam
    Nov 20 '18 at 14:44










  • If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
    – Paul H
    Nov 20 '18 at 19:02










  • @Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
    – Liam
    Nov 20 '18 at 20:46










  • what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
    – Paul H
    Nov 21 '18 at 1:15
















1














So far I have produced a Choropleth map by:



fig, ax = plt.subplots(1, figsize=(32, 16))
ax.axis('off')

df.plot(column='Income Rank', scheme='quantiles', k=7,legend=True, cmap='YlOrRd_r', ax=ax)
ax.annotate(xy=(0.1, .08), xycoords='figure fraction', horizontalalignment='left', verticalalignment='top'
,s='Income deprivation Rank. Lowest rank = most deprived.')


which looks like this:
enter image description here



My DF Looks like this:



geometry    Counts  WardCode Ward Name   Income Rank                                                                
POLYGON (()) 1545 N09000001 Abbey 3


So it plots the rank of each area in relation to income data I have in df. Is it possible for me to plot crimes on this map aswell? I am trying to show the link between low income and high crime rate.. For example, with markers or maybe use a different colour scheme to represent high crime areas? The dataframe with my crimes looks like this:



WARDNAME    Counts
0 CENTRAL 3206
1 DUNCAIRN 757
2 BLACKSTAFF 584


I also have a df of crimes that have Latitude and Longitude, that looks like this:



Crime ID    Date    Longit  Latit   Crime type  Ward Name   Ward Code
0 01 2016-01 -5.886699 54.591309 Theft CENTRAL N08000313


Is the only way I can plot both of these things on the same map by using Folium and plotting the Choropleth with the income values and then plotting the crimes as markers? Or can I do it without folium?
Thanks










share|improve this question
























  • Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
    – user32185
    Nov 20 '18 at 13:14










  • @user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
    – Liam
    Nov 20 '18 at 14:44










  • If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
    – Paul H
    Nov 20 '18 at 19:02










  • @Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
    – Liam
    Nov 20 '18 at 20:46










  • what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
    – Paul H
    Nov 21 '18 at 1:15














1












1








1







So far I have produced a Choropleth map by:



fig, ax = plt.subplots(1, figsize=(32, 16))
ax.axis('off')

df.plot(column='Income Rank', scheme='quantiles', k=7,legend=True, cmap='YlOrRd_r', ax=ax)
ax.annotate(xy=(0.1, .08), xycoords='figure fraction', horizontalalignment='left', verticalalignment='top'
,s='Income deprivation Rank. Lowest rank = most deprived.')


which looks like this:
enter image description here



My DF Looks like this:



geometry    Counts  WardCode Ward Name   Income Rank                                                                
POLYGON (()) 1545 N09000001 Abbey 3


So it plots the rank of each area in relation to income data I have in df. Is it possible for me to plot crimes on this map aswell? I am trying to show the link between low income and high crime rate.. For example, with markers or maybe use a different colour scheme to represent high crime areas? The dataframe with my crimes looks like this:



WARDNAME    Counts
0 CENTRAL 3206
1 DUNCAIRN 757
2 BLACKSTAFF 584


I also have a df of crimes that have Latitude and Longitude, that looks like this:



Crime ID    Date    Longit  Latit   Crime type  Ward Name   Ward Code
0 01 2016-01 -5.886699 54.591309 Theft CENTRAL N08000313


Is the only way I can plot both of these things on the same map by using Folium and plotting the Choropleth with the income values and then plotting the crimes as markers? Or can I do it without folium?
Thanks










share|improve this question















So far I have produced a Choropleth map by:



fig, ax = plt.subplots(1, figsize=(32, 16))
ax.axis('off')

df.plot(column='Income Rank', scheme='quantiles', k=7,legend=True, cmap='YlOrRd_r', ax=ax)
ax.annotate(xy=(0.1, .08), xycoords='figure fraction', horizontalalignment='left', verticalalignment='top'
,s='Income deprivation Rank. Lowest rank = most deprived.')


which looks like this:
enter image description here



My DF Looks like this:



geometry    Counts  WardCode Ward Name   Income Rank                                                                
POLYGON (()) 1545 N09000001 Abbey 3


So it plots the rank of each area in relation to income data I have in df. Is it possible for me to plot crimes on this map aswell? I am trying to show the link between low income and high crime rate.. For example, with markers or maybe use a different colour scheme to represent high crime areas? The dataframe with my crimes looks like this:



WARDNAME    Counts
0 CENTRAL 3206
1 DUNCAIRN 757
2 BLACKSTAFF 584


I also have a df of crimes that have Latitude and Longitude, that looks like this:



Crime ID    Date    Longit  Latit   Crime type  Ward Name   Ward Code
0 01 2016-01 -5.886699 54.591309 Theft CENTRAL N08000313


Is the only way I can plot both of these things on the same map by using Folium and plotting the Choropleth with the income values and then plotting the crimes as markers? Or can I do it without folium?
Thanks







python pandas matplotlib geopandas choropleth






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 23:55







Liam

















asked Nov 19 '18 at 19:24









LiamLiam

115113




115113












  • Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
    – user32185
    Nov 20 '18 at 13:14










  • @user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
    – Liam
    Nov 20 '18 at 14:44










  • If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
    – Paul H
    Nov 20 '18 at 19:02










  • @Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
    – Liam
    Nov 20 '18 at 20:46










  • what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
    – Paul H
    Nov 21 '18 at 1:15


















  • Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
    – user32185
    Nov 20 '18 at 13:14










  • @user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
    – Liam
    Nov 20 '18 at 14:44










  • If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
    – Paul H
    Nov 20 '18 at 19:02










  • @Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
    – Liam
    Nov 20 '18 at 20:46










  • what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
    – Paul H
    Nov 21 '18 at 1:15
















Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
– user32185
Nov 20 '18 at 13:14




Hi Liam, do you mind to share (at least a sample of) the data you are using? Does this or this ccould be useful to you?
– user32185
Nov 20 '18 at 13:14












@user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
– Liam
Nov 20 '18 at 14:44




@user32185 added some data about the data frame I am using to plot the current map.. Is this what you wanted?
– Liam
Nov 20 '18 at 14:44












If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
– Paul H
Nov 20 '18 at 19:02




If I understand correctly, you can call the plot method of the other geodataframe, being sure to pass the same Axes object to it.
– Paul H
Nov 20 '18 at 19:02












@Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
– Liam
Nov 20 '18 at 20:46




@Paul H I was able to do this but the second plot just basically overwrites the first so I can't see any of the ranks anymore, its just the crimes plotted.. Can I reduce one so that I can see both?
– Liam
Nov 20 '18 at 20:46












what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
– Paul H
Nov 21 '18 at 1:15




what do you mean by "reduce"? Are these both polyon layers? I would plot the ranks as points in the centroids of the polygons with a higher z-order than the first set of polygons.
– Paul H
Nov 21 '18 at 1:15












1 Answer
1






active

oldest

votes


















0














For choropleth maps with 2 overlaying layers of polygons, you need to use (semi or) transparent plots on top layer. Let me demonstrate with this example. You need to install geopandas to run this.



import geopandas as gpd
import matplotlib.pyplot as plt

# load world data (provided with geopandas)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# select some countries (for top layer plots)
brazil = world[world.name == u'Brazil']
russia = world[world.name == u'Russia']

# grouping countries by continents for base layer
world = world[['continent', 'geometry']] # for grouping purposes, take 2 columns
continents = world.dissolve(by='continent') # only column 'geometry' is retained; no aggregated attribute

# plot world's continents first as base layer
ax1 = continents.plot(figsize=(12, 8), cmap='Set2')

# plot other polygons on top of the base layer
# 'facecolor' = 'None' specifies transparent area
# plot Brazil at upper level (zorder=11) using 'hatch' as symbol
# higher value of zorder causes the plot on top of layers with lower values
kwarg3s = {'facecolor': 'None', 'edgecolor': 'green', 'linewidth': 1.5, 'hatch': '|||'}
brazil.plot(zorder=11, ax=ax1, **kwarg3s)

# plot Russia at upper level using 'hatch' as symbol
kwarg4s = {'facecolor': 'None', 'edgecolor': 'red', 'linewidth': 0.5, 'hatch': 'xx'}
russia.plot(zorder=11, ax=ax1, **kwarg4s)
plt.show()


The resulting plot:
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%2f53381311%2fmatplotlib-choropleth-map-plotting-two-different-pieces-of-data%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














    For choropleth maps with 2 overlaying layers of polygons, you need to use (semi or) transparent plots on top layer. Let me demonstrate with this example. You need to install geopandas to run this.



    import geopandas as gpd
    import matplotlib.pyplot as plt

    # load world data (provided with geopandas)
    world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

    # select some countries (for top layer plots)
    brazil = world[world.name == u'Brazil']
    russia = world[world.name == u'Russia']

    # grouping countries by continents for base layer
    world = world[['continent', 'geometry']] # for grouping purposes, take 2 columns
    continents = world.dissolve(by='continent') # only column 'geometry' is retained; no aggregated attribute

    # plot world's continents first as base layer
    ax1 = continents.plot(figsize=(12, 8), cmap='Set2')

    # plot other polygons on top of the base layer
    # 'facecolor' = 'None' specifies transparent area
    # plot Brazil at upper level (zorder=11) using 'hatch' as symbol
    # higher value of zorder causes the plot on top of layers with lower values
    kwarg3s = {'facecolor': 'None', 'edgecolor': 'green', 'linewidth': 1.5, 'hatch': '|||'}
    brazil.plot(zorder=11, ax=ax1, **kwarg3s)

    # plot Russia at upper level using 'hatch' as symbol
    kwarg4s = {'facecolor': 'None', 'edgecolor': 'red', 'linewidth': 0.5, 'hatch': 'xx'}
    russia.plot(zorder=11, ax=ax1, **kwarg4s)
    plt.show()


    The resulting plot:
    enter image description here






    share|improve this answer


























      0














      For choropleth maps with 2 overlaying layers of polygons, you need to use (semi or) transparent plots on top layer. Let me demonstrate with this example. You need to install geopandas to run this.



      import geopandas as gpd
      import matplotlib.pyplot as plt

      # load world data (provided with geopandas)
      world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

      # select some countries (for top layer plots)
      brazil = world[world.name == u'Brazil']
      russia = world[world.name == u'Russia']

      # grouping countries by continents for base layer
      world = world[['continent', 'geometry']] # for grouping purposes, take 2 columns
      continents = world.dissolve(by='continent') # only column 'geometry' is retained; no aggregated attribute

      # plot world's continents first as base layer
      ax1 = continents.plot(figsize=(12, 8), cmap='Set2')

      # plot other polygons on top of the base layer
      # 'facecolor' = 'None' specifies transparent area
      # plot Brazil at upper level (zorder=11) using 'hatch' as symbol
      # higher value of zorder causes the plot on top of layers with lower values
      kwarg3s = {'facecolor': 'None', 'edgecolor': 'green', 'linewidth': 1.5, 'hatch': '|||'}
      brazil.plot(zorder=11, ax=ax1, **kwarg3s)

      # plot Russia at upper level using 'hatch' as symbol
      kwarg4s = {'facecolor': 'None', 'edgecolor': 'red', 'linewidth': 0.5, 'hatch': 'xx'}
      russia.plot(zorder=11, ax=ax1, **kwarg4s)
      plt.show()


      The resulting plot:
      enter image description here






      share|improve this answer
























        0












        0








        0






        For choropleth maps with 2 overlaying layers of polygons, you need to use (semi or) transparent plots on top layer. Let me demonstrate with this example. You need to install geopandas to run this.



        import geopandas as gpd
        import matplotlib.pyplot as plt

        # load world data (provided with geopandas)
        world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

        # select some countries (for top layer plots)
        brazil = world[world.name == u'Brazil']
        russia = world[world.name == u'Russia']

        # grouping countries by continents for base layer
        world = world[['continent', 'geometry']] # for grouping purposes, take 2 columns
        continents = world.dissolve(by='continent') # only column 'geometry' is retained; no aggregated attribute

        # plot world's continents first as base layer
        ax1 = continents.plot(figsize=(12, 8), cmap='Set2')

        # plot other polygons on top of the base layer
        # 'facecolor' = 'None' specifies transparent area
        # plot Brazil at upper level (zorder=11) using 'hatch' as symbol
        # higher value of zorder causes the plot on top of layers with lower values
        kwarg3s = {'facecolor': 'None', 'edgecolor': 'green', 'linewidth': 1.5, 'hatch': '|||'}
        brazil.plot(zorder=11, ax=ax1, **kwarg3s)

        # plot Russia at upper level using 'hatch' as symbol
        kwarg4s = {'facecolor': 'None', 'edgecolor': 'red', 'linewidth': 0.5, 'hatch': 'xx'}
        russia.plot(zorder=11, ax=ax1, **kwarg4s)
        plt.show()


        The resulting plot:
        enter image description here






        share|improve this answer












        For choropleth maps with 2 overlaying layers of polygons, you need to use (semi or) transparent plots on top layer. Let me demonstrate with this example. You need to install geopandas to run this.



        import geopandas as gpd
        import matplotlib.pyplot as plt

        # load world data (provided with geopandas)
        world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

        # select some countries (for top layer plots)
        brazil = world[world.name == u'Brazil']
        russia = world[world.name == u'Russia']

        # grouping countries by continents for base layer
        world = world[['continent', 'geometry']] # for grouping purposes, take 2 columns
        continents = world.dissolve(by='continent') # only column 'geometry' is retained; no aggregated attribute

        # plot world's continents first as base layer
        ax1 = continents.plot(figsize=(12, 8), cmap='Set2')

        # plot other polygons on top of the base layer
        # 'facecolor' = 'None' specifies transparent area
        # plot Brazil at upper level (zorder=11) using 'hatch' as symbol
        # higher value of zorder causes the plot on top of layers with lower values
        kwarg3s = {'facecolor': 'None', 'edgecolor': 'green', 'linewidth': 1.5, 'hatch': '|||'}
        brazil.plot(zorder=11, ax=ax1, **kwarg3s)

        # plot Russia at upper level using 'hatch' as symbol
        kwarg4s = {'facecolor': 'None', 'edgecolor': 'red', 'linewidth': 0.5, 'hatch': 'xx'}
        russia.plot(zorder=11, ax=ax1, **kwarg4s)
        plt.show()


        The resulting plot:
        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 8:12









        swatchaiswatchai

        2,82021424




        2,82021424






























            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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • 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%2f53381311%2fmatplotlib-choropleth-map-plotting-two-different-pieces-of-data%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

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            Npm cannot find a required file even through it is in the searched directory