Create Excel Freeform Shapes from Polygons

How to transfer polygon data into freeform shapes in Microsoft Excel

Create Excel Freeform Shapes from PolygonsIf you are a regular reader or even subscribed to this blog, you will not be surprised to hear that I am working on a new challenge regarding maps in Microsoft Excel.

We had a lot of articles already on how to create Choropleth Maps in Microsoft Excel. The new project is about using maps in Excel again, but with a different type of visualization.

Since I am just starting out on this challenge, I can’t provide more details yet.

Having said that, for the preparation of the new project, I had to work with geographical polygon data. Now, what’s this?

A polygon is […] a plane figure that is bounded by a finite chain of straight line segments closing in a loop to form a closed chain or circuit.” (source: Wikipedia).

In the context of geographical visualization, a polygon represents a region (e.g. country) on a map. Such a polygon consists of a series of geographical points: pairs of latitude and longitude in a defined order (path). If you draw an outline through these points in the given order, you get a shape forming the boundary of this region.

And this was my challenge: transfer geographical polygon data into freeform shapes in Microsoft Excel. I am not sure, but I thought maybe some of you might be interested, so I decided to share my solution.

Today’s post first shows how to plot polygon data on standard Excel XY Scatter charts and then describes my solution to transfer the data into freeform shapes. As always, the article provides a link to download the Excel workbook for free.


The Data

The underlying database is a simple, but huge Excel table with the polygon data of the borders of all countries in the world:

Polygon Database

The table contains the ISO3 abbreviation, the country name, the polygon ID, the point order, the latitude and the longitude. As I said, simple, but huge: more than 400,000 rows.

I created this polygon data from an ESRI Shapefile of a world map using Richard Leeke’s fantastic ShapeToTab utility (more here: Create Your Own Filled Maps in Tableau). Many thanks go again to Richard for his fabulous tools TabGeoHack and ShapeToTab.

As you can see in the screenshot for the example of Aruba, the first and last point have identical latitude and longitude values: the 19 points make a closed chain, i.e. the polygon of Aruba’s boundaries.

Plotting Polygons in an XY Scatter Chart

You can directly plot the polygons on an XY Scatter chart in Excel. No data preprocessing or even coding necessary. All you have to do is to adjust the minimum and maximum values of the two axes. Let’s first try a smaller example than the world map. Here is the polygon of Austria plotted in an XY Scatter chart:

Austria XY Scatter

You can already recognize Austria, right? Changing the chart type to an XY Scatter with smoothed or straight lines and no markers makes it even clearer:

Austria XY Scatter Lines no Markers

A short distraction, if you don’t mind: I love watching The Big Bang Theory, but I simply can’t see how Austria on a map looks like a Wiener:

What kind of Wiener are they eating?

Fun fact: in Austria, Wiener are actually called Frankfurter. But I am digressing. “Focus attenuation” (fits well, doesn’t it?). Reading the last paragraph back, I noticed I am sounding like Sheldon already. So, back to the polygons and maps.

Let’s have a look at Germany. The simple XY scatter:

Germany XY Scatter

And the same data plotted on an XY Scatter with lines and no markers:

Germany XY Scatter Lines no Markers

What is going on here? Well, unlike Austria, Germany consists of more than one polygon (23 to be precise):

Polygons of Germany

Since all data is plotted in one data series, Excel is also drawing lines between the start and end points of the different polygons. To avoid this, we would have to plot the data in 23 separate data series or remove the unwanted lines manually or by VBA.

This becomes a real problem, if you have a lot of polygons in your data. The world map, for instance, consists of 3,775 polygons. Since the maximum number of data series in an Excel chart is 255 (Excel Specifications and Limits), the option of having one data series per polygon is out of the picture. A VBA routine to delete all unwanted connection lines between the polygons is the only reasonable way to solve this issue.

Having said that, with very large data sets like the world map, you may even go with a XY Scatter chart with markers only and no lines:

World XY Scatter

So much for plotting polygons on Excel charts.

The Challenge

The problem I was facing in my project was different. I didn’t want to plot polygons on an XY Scatter chart. I rather needed to transfer them into freeform shapes. A picture says a thousand words: this is what I was after:

World Map Freeform Shapes

A map in Excel made of freeform shapes (exactly like the ones we used in all the Choropleth Maps in Microsoft Excel posts) automatically created from the raw polygon data table shown above.

The Implementation

Before starting to code the VBA subs, we have to do a few enhancements on the worksheet:

  • add a unique identifier for every polygon (ISO3 abbreviation followed by an underscore followed by the Polygon ID). A simple string concatenation
  • add two columns to transfer Latitude and Longitude into positive values in points on a worksheet. The formulas are very simple: basic arithmetical operations based on maximum and minimum values of Latitude and Longitude and three parameters (scale, top and left offset)

Now on to the VBA code.

The heart of the solution is the Shapes.AddPolyline Method. Calling this method with “an array of coordinate pairs that specifies the polyline drawing’s vertices” creates a freeform shape of the closed polygon. This method makes the implementation a walk in the park:

The sub to create freeform shapes simply loops through the entire data table, transfers the X and Y points of each polygon to an array and calls the .AddPolyline method with this array to insert the freeform shape.

The VBA project is open, the code is commented and very slim (132 lines). I think I do not have to go into the details here. If you are interested, download the workbook (download link at the end of the post) and have a look. If you have any questions, please feel free to leave me a comment.

How to use the Tool

The workbook (download link see below) consists of only two worksheets: one with the polygon data and a few simple calculations and an output sheet for the freeform shapes.

On the data sheet, the first 6 columns of the table contain the polygon data. The next 3 columns create a unique ID for each polygon and transfer Latitude and Longitude into valid positions (points) on the output sheet using simple formulas (see section above):

Data Table

The VBA procedures can be started from an extra tab on the ribbon (POLYGONS 2 SHAPES):

POLYGONS 2 SHAPES Tab

A click on one of the first three buttons on this tab starts the VBA routines:

  • Transfer the polygon data into freeform shapes on the output sheet
  • Delete all shapes on the output sheet
  • Create groups of shapes for each country (if the country has more than one polygon)

Clicking on the last icon is simply sending you to this blog. You see, I am desperately looking for options to increase the traffic here.

If you want to use the tool for your own polygons, you simply have to clear the first 6 columns of the table on the data worksheet, copy in your own data, resize the table and finally click on the first icon of the POLYGONS 2 SHAPES tab. That’s it. A few seconds later you should have the freeform shapes on the output sheet.

The Disadvantage: Performance

The code isn’t optimized for performance and it takes some time to transfer the polygon data into freeform shapes. The polygons of Europe (without Russia and Greenland), for instance, consist of more than 55,000 rows. Creating 476 freeform shapes of 52 countries takes between 5 and 6 seconds on my machine. Not really fast, but sufficient for my purposes.

The Download Link

Here is the Excel workbook with the polygon data of Europe (without Russia and Greenland) for free download:

Download Create Shapes from Polygons (zipped Excel 2010-2013 workbook, 4.4 MB)

Stay tuned.

Comments

34 responses to “Create Excel Freeform Shapes from Polygons”

  1. CristianS Avatar

    How about using Qgis for making polygons from points?

  2. Robert Avatar

    Cristian,
    I am not claiming Excel would be the best tool to do it. However, I need the routine as a part of a another Excel project I am working on. Using another tool was not an option.

  3. CristianS Avatar

    Ok. Qgis it’s open source. The idea was just to transform the polygons in the way you want, prior to paste in Excel. It’s a way to easy learn the gis stuff.

  4. Robert Avatar

    Cristian,
    you are right, if you need a one-off solution to create freeform shapes from polygon data, QGIS is probably the easier way.
    What I needed was a VBA routine in a stand-alone Excel workbook doing this again and again on user input. That’s why I created the workbook published above.

  5. Stefan Sandauer Avatar
    Stefan Sandauer

    Hi Robert, as i did all the work for all the districts and cities of Austria by hand, – with a Little VBA help… Your solution is awesome.
    To give a little hint for the difference between Wiener and Frankfurter (as i am coming from Vienna): the only difference is the method in making the sausages – the ingredients differ a little bit – and the behavior in Austria in naming things. The original founder (…) was a butcher from Frankfurt, coming to Vienna. Here, he added beef (veal)to the sausages. Some years later, the sausages where vernacularly called Frankfurter…
    cheers ,
    Stefan

  6. Mike Avatar
    Mike

    Hello Robert,
    As someone who has followed your blog for a while, I would like to thank you for sharing this information.
    It is very creative and insightful. I have learned a great deal from it.
    Thanks,
    Mike

  7. CristianS Avatar

    I finally understood why you used this approach. Very interesting!
    Have you try to export from Qgis a form in your format?
    I tried for myself, but, somehow, it didn’t work. My image looks more like your Germany scatter plot than what I expected.
    I’ve exported the geometry with MMQgis plugin and used in your file. But something I’ve mised.
    Thank you for your example (all your examples, actually). A true inspiration!

  8. Robert Avatar

    Cristian,
    I never used Qgis, so I unfortunately I can’t help you here. I am sorry.

  9. PereR Avatar

    It’s great script. It’s only a pity it doesn’t work. I need some hint what’s I’m doing wrong – just copied my data from shp file and filled table in the same manner as in example and code works to the end but there are no polygons. Maybe Excel 2016 is not compatible? I’d like to know, because I need this polygons.

  10. PereR Avatar

    Ok. I’ve found my error, that was wrong projection x, y – bad scale coordinates. Cheers!

  11. Flavio Henrique da Silva Avatar
    Flavio Henrique da Silva

    hi, Robert Clearlyandsimply.com,
    please make new Tutorial or explain more about the problem of plot the coordinates with lines and broke the series to make this issue.
    i am want this code and this approach to create this Scatter Charts with lines and create Freeform Shapes with split series, no problem the limit of Excel.
    you are Greate.
    please.

  12. Robert Avatar

    Flavio,
    I am not sure I understand your question correctly, but if you have polygon data that form more than one shape and want to plot it on an XY scatter chart, you need more than one data series in your XY scatter chart. Simply add one data series per polygon data series which form one consistent shape and Excel will do the rest.
    If you want to create freeform shapes from your polygon data, you can directly use the workbook I provided for download. No changes necessary.

  13. Flavio Henrique da Silva Avatar
    Flavio Henrique da Silva

    Hi Robert,
    thank you very mutch,
    but i am not understand.
    I need solution about wrong Zig-Zag Lines to Geramany Map using 2 ways: VBA Plot Shapes and Plot Chart.
    if this workbook file it is the solution, i need copy of the problem (xml file, chart of wrong lines) to i understand.
    i need the original xml file with original coordinates, the wrong chart with wrong lines zig-zag points, and how insert the “blank lines” into series to make the correct chart.
    i want make the “way of plot chart ” and “vba way of plot shapes” of coordinates to solution the problem of wrong zig-zag lines, i want import the xml and plot them.
    an vba routine to delete wrong zig-zag lines on chart is other way i want.
    please more sample file and instructions, i have worked hard in this problem.
    please copy of your xml files of World Map and Germany map and workbook of GErmany charts (and wrong Germany chart).
    thank you.
    Flavio Henrique.

  14. Robert Avatar

    Flavio,
    I already sent you an email with another workbook.

  15. Flavio Henrique da Silva Avatar
    Flavio Henrique da Silva

    Thank you very mutch Robert!
    awesome!
    i looking now to original xml files of this coordinates.
    cheers!

  16. Iz Avatar
    Iz

    Hi:
    Thanks very much for posting such valuable tips and information!
    I am trying to find a way to organize coordinates into a polygon. Maybe this is something you have done and have a solution (hoping!).
    I have a set of coordinates in random order that, if ordered correctly, would form a polygon. In their current order, they are a huge pile of zig-zag lines in Excel XY chart.
    How can I sort them to properly draw a polygon in Excel XY chart?
    Thanks very much for any help or pointers.

  17. Robert Avatar

    Iz,
    a polygon data set usually includes the X and Y coordinates (in most cases longitude and latitude) and a point order ID. The point order is crucial. If it is missing, the data simply provides the coordinates of the data points, but no information how they form a polygon.
    If your data set lacks this point order information, I do not see a way how you could generate or calculate it simply based on the X and Y data points. How should that be possible? Using an algorithm like a simple Nearest Neighbor? This wouldn’t work, because very often, the next point in the point order of a polygon is not the nearest neighbor.
    I am sorry, but I do not see a way how this could be solved. I assume you have to look for a polygon data set including the point order information.

  18. angelamoss@nhs.net Avatar
    angelamoss@nhs.net

    Hi Thank you for your template it works great. I am using it for health boundaries in England clinical commissioning groups. I have downloaded the mapping files from Office of National Statistics Geo portal as a mid mif file opened in MapInfo and then exported longitude and latitude coordinates.
    The resulting polygons provide a squashed version of England, too short and wider than expected. Can you shine any light on why this would be please. The projection looks fine in MapInfo.

  19. Robert Avatar

    Angela,
    the code I am using in my tool is not changing or projecting the polygon data, but rather simply creates freeform shapes according the X and Y values on the data sheet using the .AddPolyline method of the Shapes object in VBA.
    If the polygon data created by MapInfo results in a distorted freeform shape in Excel, I would assume that MapInfo e.g. exports the polygon data without the Mercator Projec-tion (https://en.wikipedia.org/wiki/Mercator_projection). I can’t tell you for sure, though, this is just a wild guess.
    In any case, it has nothing to do with my code, because the code simply and mindlessly draws a polygon of the values on the data sheet.

  20. Chris Avatar
    Chris

    Hey man,
    Thanks for the great work! Really nice to know how to make your own world-map 🙂
    I was wondering though how to get the polygons for the whole world.. I am quite some IT-newbie and I have an .shp file from http://thematicmapping.org/downloads/world_borders.php. Do you know how to get the data to Excel?
    Thanks sooo much in advance 🙂
    Best regards,
    Chris

  21. Robert Avatar

    Chris,
    if you only need a world map in Excel, have a look at this post:

    Choropleth Maps with Excel

    If you need the map created from polygons, have a look at this link:
    Download create_shapes_from_polygons_world (45 MB)
    This is the map I created from polygons using the tool described above.

  22. Keith Avatar
    Keith

    Robert, truly outstanding website. Please keep it up.
    Re. the quandary of Excel’s limitation for plotting 255 polygons, here’s a workaround: Use a blank row in the spreadsheet data to break it into separate polygons. Plot the example below (including the blank row) as a single series (XY scatter with lines), and it will appear as “separate polygons”. Remove the blank line, and you’ll see a line connecting the polygons.
    X Y
    1 1
    1 2
    2 2
    2 1
    1 1
    3 2
    4 2
    4 1
    3 1
    3 2

  23. Tim Avatar
    Tim

    Hi Robert,
    Many thanks for sharing this work – very helpful. Is there any chance you can share the world dataset again? (the workbook appears to be corrupted in the above post)
    Thanks again,
    Tim

  24. Robert Avatar

    Tim,
    I just double checked. The link is still working and the file is not corrupt. It is a huge workbook (45 MB, more than 400,000 data rows), so it takes a while to open it, but it is not corrupt.

  25. Utku Avatar
    Utku

    Hi Robert,
    Thank you so much for this fantastic work.
    Is it possible to specify different colors for each country?
    Thanks again.

  26. Robert Avatar

    Utku,
    this is possible.
    There are different options:
    Option 1: Format the fill color during the creation of the shapes
    The following line of code (line 77) currently assigns a dark grey fill color of the lines to all freeform shapes:
    .Line.ForeColor.RGB = RGB(100, 100, 100)
    If you want to have individual line colors for each shape, you need to define the color coding for the shapes (countries) somewhere on a worksheet (in tab [Data] for instance) and then change the code to use the defined line color per shape.
    Option 2: Format the fill color of lines after the creation of the shapes
    For this option, you would add a loop at the end of the code (after all shapes have been created), loop through all shapes and format the lines as specified somewhere on a worksheet.

  27. Utku Avatar
    Utku

    Hi Robert,
    I used the 1st option.
    Thanks a lot.
    Utku

  28. Łukasz Avatar
    Łukasz

    Dear Robert,
    Great work. Special Thanks for sharing the files for free.

  29. Martin Aldridge Avatar
    Martin Aldridge

    Have you got any further in this and have other continents

  30. Robert Avatar

    Martin,
    no, I haven’t. But you can still use the workbook posted above to create freeform shapes from polygons for any continent or region on your own.

  31. phanter Avatar
    phanter

    You don’t by any chance have the polygons for all the oceans?

  32. Robert Avatar

    phanter,
    I do not have the polygons of the oceans, but they should be available somewhere.
    Try openstreetmap.org or marineregions.org, for instance.

Leave a Reply to Iz Cancel reply

Your email address will not be published. Required fields are marked *