<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hong Gao on Medium]]></title>
        <description><![CDATA[Stories by Hong Gao on Medium]]></description>
        <link>https://medium.com/@honggao?source=rss-1ab550e0fa82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ULQoxzWkS1A__EKq.jpg</url>
            <title>Stories by Hong Gao on Medium</title>
            <link>https://medium.com/@honggao?source=rss-1ab550e0fa82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:24:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@honggao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Plot Polygons with ggplot2]]></title>
            <link>https://medium.com/@honggao/plot-polygons-with-ggplot2-b5a87e4fa602?source=rss-1ab550e0fa82------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a87e4fa602</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hong Gao]]></dc:creator>
            <pubDate>Mon, 20 May 2019 22:58:47 GMT</pubDate>
            <atom:updated>2019-05-20T22:58:47.214Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will introduce how to create spatial polygon maps with <a href="http://had.co.nz/ggplot2/"><em>ggplot2</em></a>, a popular R visualization package. <em>ggplot2</em> is the most used plotting tool in R and has been adapted in various statistical graphics. It’s powerful in a way that it’s extremely flexible to adjust any parts and details in the plots to generate highly customized graphics (we will go into more details on this later). Because of its popularity, there are many good resources online to walk through almost all kinds of plots. Here are a couple links I find are very helpful:</p><ul><li><a href="https://www.springer.com/us/book/9780387981413">An awesome <em>ggplot2</em> book</a> written by <a href="http://hadley.nz/">Hadley Wickham</a>, creator of the package. The book is worth buying, but there is <a href="https://github.com/hadley/ggplot2-book">a publicly available version on Github</a>. You’ll need to run a few command lines to compile the book.</li><li><a href="http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html">50 applicable examples of <em>ggplot2</em> visualizations</a>. Once you become familiar with the package, it’s easy to use the examples and change it a little for your own use.</li><li><a href="https://datacarpentry.org/dc_zurich/R-ecology/05-visualisation-ggplot2.html">Some more examples</a>.</li><li>Google and Stack Overflow of course, are the best places to look for answers if you are stuck.</li></ul><p>Despite all the tutorials online, I found it’s tricky to locate an easy but comprehensive tutorial for visualizing spatial data with <em>ggplot2</em>. When I first got to know mapping, I used ArcGIS. It is a great tool, however, the license is expensive. It was also not yet strong enough to perform spatial analysis when I switched to R around 2014. I had to search all over the internet, look for books, and try all kinds to packages only to realize that the best package to plot maps in R is the package I use everyday for plotting dots, boxes, lines. Once again, I hope this blog post will provide helpful code examples for plotting static spatial polygon maps with <em>ggplot2</em>.</p><p>One more thing before we get started, colors are essential components of a pretty map. <a href="http://colorbrewer2.org/#type=sequential&amp;scheme=BuGn&amp;n=3">Color Brewer</a> is a good website to look for the best color scheme. The HEX code can be directly called in R. There is also a package for colors in R, called <a href="https://www.rdocumentation.org/packages/RColorBrewer/versions/1.1-2/topics/RColorBrewer"><em>RColorBrewer</em></a>, we’ll be using it for this post. I also find myself repeatedly going to this <a href="https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf">R color cheat sheet</a> to locate names of the colors I want, so it’s good to keep it handy. Alright, let’s get started.</p><h3>Install ggplot2 in R</h3><p>If you already have <em>ggplot2</em> and <em>RColorBrewer</em> installed in your Rstudio, you can skip this section. If you’re new to R, I recommend using <a href="https://www.rstudio.com/">Rstudio</a>, a clean shell program for R. Set up your Rstudio following instructions <a href="https://jennybc.github.io/2014-05-12-ubc/r-setup.html">here</a>. To install <em>ggplot2 </em>and<em> RColorBrewer</em>, simply type the following lines in Rstudio console:</p><pre>install.packages(&#39;ggplot2&#39;)<br>install.packages(&#39;RColorBrewer&#39;)</pre><p>To activate the package, type:</p><pre>library(ggplot2)<br>library(RColorBrewer)</pre><h3>Data Preparation</h3><p>Before going into visualization, we need some spatial polygon data and some other data we want to plot with. If you want to dive right in to plotting, no problem, I put all the data you need on <a href="https://github.com/honggao110/MediumBlog_R">my Github</a>. Download the data, and you’re ready to skip this section and start plotting.</p><p>If you are curious about data preparation, let’s walk through it in this section. We’ll use a publicly available New York City (NYC) Zip Code boundary map. Download the file from <a href="https://data.cityofnewyork.us/Business/Zip-Code-Boundaries/i8iw-xf4u?category=Business&amp;view_name=Zip-Code-Boundaries">here</a>, unzip it, and save the <em>ZIP_CODE_040114</em> folder to a folder you like. All the seven files make up the <a href="https://en.wikipedia.org/wiki/Shapefile">shapefile</a> (basically the map) of the NYC Zip Code boundary map. To read it into R, we’ll use a package specifically for processing spatial data, <em>rgdal</em>. The first step is still installing and activating the package:</p><pre>install.packages(&#39;rgdal&#39;)<br>library(rgdal)</pre><p>Then, point R to the folder you placed the <em>ZIP_CODE_040114</em> folder, and read it in. Comments and explanation of what the following code does is after the <strong><em>#</em></strong> sign.</p><pre># replace this file path with your own<br>filepath = &quot;~/Documents/HongGao/MediumBlog_R/1.ggplot2_polygon&quot; <br># set directory to the file path<br>setwd(filepath)<br># read in the shapefile and name it zipcode<br>zipcode &lt;- readOGR(&quot;ZIP_CODE_040114/&quot;, &quot;ZIP_CODE_040114&quot;)</pre><p>You should see this message indicating you successfully loaded the data:</p><blockquote>OGR data source with driver: ESRI Shapefile <br>Source: “/Users/HongG/Documents/HongGao/MediumBlog_R/1.ggplot2_polygon”, layer: “ZIP_CODE_040114”<br>with 263 features<br>It has 12 fields</blockquote><p>Also, in the upper right window of Rstudio, you should see your zipcode data as a Large<strong><em> SpatialPolygonDataFrame</em></strong>. This is how R names spatial polygon data, and the data frame means there’s some data associated with the polygon. This is very import for plotting the map because all the information for each polygon, i.e., name, area, population, and demographics, is stored in a table with each row corresponding to a polygon. It is crucial to maintain the current sequence of rows during data manipulation, because if any of the rows are misplaced, your polygon can no longer find the right data to display. We won’t run any analysis today to distort the sequence, but it’s always a good practice to manually generate a sequential ID for each row.</p><pre># generate a unique ID for each polygon<br>zipcode@data$seq_id &lt;- seq(1:nrow(zipcode@data))</pre><p>A quick look at the map:</p><pre>plot(zipcode)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZvLyTAqPj6sh1x1Dm1S7Q.png" /></figure><p>Now we have a nice blank outline map, let’s generate some data so we can color it. We’ll generate two types of data, one is continuous, one is categorical, so after this practice, you’ll be comfortable to deal with any situation. New generated data will be new columns in the polygon data frame. We’ll also generate some missing data, so it’s more reasonable.</p><pre># generate random numbers from a uniform distribution<br>zipcode@data$continuous_var &lt;- runif(nrow(zipcode@data))<br># create some missing data, NAs<br># values below 0.1 are changed to NA<br>zipcode@data[zipcode@data$continuous_var&lt;0.1,]$continuous_var &lt;- NA</pre><p>We bin the <em>continuous_var</em> to three categories with its 33th and 66th percentile and call it <em>categorical_var</em>. Missing data (NA) is preserved in the new column.</p><pre>zipcode@data$categorical_var &lt;- <br>.bincode(zipcode@data$continuous_var, <br>breaks = quantile(zipcode@data$continuous_var, seq(0,1,0.33), <br>na.rm = T), include.lowest = T)</pre><p>Now we are ready to plot!</p><h3>Plot Polygons</h3><p><em>ggplot2</em> does not process spatial polygon data frame directly. In order for it to work, we first need to transfer the polygons into a data frame. This process is called <strong><em>fortify</em></strong>, which is a function inside the <em>ggplot2</em> package. This function basically ‘stretches’ the polygons to a data frame where each row represents an edge of the polygon. <strong><em>fortify</em></strong> function needs a unique ID to merge the fortified geometry and the data, so we first create an <em>id</em> variable and then perform the merge.</p><pre># in order to plot polygons, first fortify the data<br>zipcode@data$id &lt;- rownames(zipcode@data)</pre><pre># create a data.frame from our spatial object<br>zipcodedata &lt;- fortify(zipcode, region = &quot;id&quot;)</pre><pre># merge the &quot;fortified&quot; data with the data from our spatial object<br>zipcodedf &lt;- merge(zipcodedata, zipcode@data,<br>                           by = &quot;id&quot;)</pre><h4>On Continuous Variable</h4><p>We first plot our continuous variable. We start by defining our plot inside ggplot() , and then add on our specific requirements.</p><pre>p0 &lt;- ggplot(data = zipcodedf, aes(x = long, y = lat, group = group, fill = continuous_var)) +<br>geom_polygon() +<br>geom_path(color = &quot;white&quot;, size = 0.2) +<br>scale_fill_gradient(breaks=c(0.33,0.66,0.99), labels=c(&quot;Low&quot;,&quot;Medium&quot;,&quot;High&quot;)) + <br>coord_equal() +<br>theme(panel.background=element_blank())+<br>theme(panel.background= element_rect(color=&quot;black&quot;)) +<br>theme(axis.title = element_blank(), axis.text = element_blank()) +<br>labs(title = &quot;Attrition Rate by New York City Zip Code&quot;)<br>print(p0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJfK-spAzG0S5DaiuruB6Q.png" /></figure><p>Let me explain what each line is doing.</p><p>ggplot(data = zipcodedf, aes(x = long, y = lat, group = group, fill = continuous_var)) We use this line to define the data frame we want to plot on. X axis is plotted on <em>long</em> variable, and Y axis is plotted on <em>lat</em> variable. <em>group</em> is an automatically generated identifier for each individual polygon. <em>fill</em> indicates which variable the colors will be based on.</p><p>geom_polygon() tells <em>ggplot2</em> we are plotting spatial polygons. Without specifying this, <em>ggplot2</em> won’t be able to identify the type of data we are working with.</p><p>geom_path(color=&quot;white&quot;, size=0.2) defines the color and size of polygon outlines, which are white and 0.2.</p><p>scale_fill_gradient(breaks=c(0.33,0.66,1), labels=c(&quot;Low&quot;,&quot;Medium&quot;,&quot;High&quot;)) Since we are plotting on a continuous variable, we arbitrarily set breaks so there are reference levels on the legend. You can use different levels by changing the breaks in the code and the labels, and the legend will change accordingly.</p><p>coord_equal() sets the ratio of x and y units. In this map, we set the ratio to 1, meaning the display ratio of longitude and latitude is 1:1.</p><p>We use theme() to define the background of the plot. The default background color in <em>ggplot2</em> is grey. For this map, I changed the background color to blank, which is white, with panel.backgound=element_blank(), so we have enough color contrast. We need the figure to have an outline, so we use panel.background = element_rect(color=&quot;black&quot;) to draw a black rectangle around the figure.</p><p>Then we disable the axis labels and axis ticks labels with theme(axis.title = element_blank(), axis.text = element_blank()).</p><p>Last, we define the title of our plot by labs(title = “title&quot;)</p><p>Call plot(), the figure we defined is plotted. All the arguments above can be changed for your aesthetic choices.</p><h4>On Categorical Variable</h4><p>Next, let’s plot on our categorical variable. We didn’t need to define the color scheme of the last map, but for this map, we have the freedom to choose our own colors. We use <em>RColorBrewer</em> for this.</p><p>First, we go to <a href="https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf">R color cheatsheet</a> to pick a favorite palette. I’ll pick <em>Blues</em>.</p><pre>display.brewer.pal(6, &quot;Blues&quot;)</pre><p>This line displays the colors in the palette. The first argument says how many colors you want. The second argument is the palette you pick. Different palette has different upper limit number, you can try it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D16mVLj1VsBICqpz8ML0hg.png" /></figure><p>This is the colors we got. To know the color code,</p><pre>brewer.pal(6, &quot;Blues&quot;)</pre><p>[1] “#EFF3FF” “#C6DBEF” “#9ECAE1” “#6BAED6” “#3182BD” “#08519C”</p><p>These code are used in the following block.</p><pre>p1 &lt;- ggplot(data = zipcodedf, aes(x=long, y=lat, group = group, fill=addNA(factor(categorical_var)))) +<br>    geom_polygon()  +<br>    geom_path(color = &quot;white&quot;, size = 0.2) +<br>    scale_fill_manual(<br>         values=c(&quot;#08306B&quot;, &quot;#4292C6&quot;,&quot;#C6DBEF&quot;,&quot;#666666&quot;), <br>         breaks= c(&quot;3&quot;,&quot;2&quot;,&quot;1&quot;,&quot;NA&quot;), <br>         labels= c(&quot;High&quot;,&quot;Medium&quot;,&quot;Low&quot;,&quot;NA&quot;))+<br>    coord_equal() +<br>    theme(panel.background=element_blank())+<br>    theme(panel.background= element_rect(color=&quot;black&quot;)) +<br>    theme(axis.title = element_blank(), <br>         axis.text = element_blank()) +<br>    labs(title = &quot;Attrition Rate by New York City Zip Code&quot;, <br>         fill = &quot;Attrition Rate&quot;)<br>print(p1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSYGxNtcXVInExnQb0xe9A.png" /></figure><p>Some of the code are the same as the continuous plot. Let me explain the different part.</p><p>In the first line with ggplot(), instead of using categorical_var directly, we use fill = addNA(factor(categorical_var)). This is categorical variables have to be in the format of factor for R to recognize. If the variable is numeric, even though it represent levels, R would still treat it as numbers. This is done by calling factor(). Also, there are some areas with no data, so we want to fill it with missing values, NA, with addNA().</p><pre>scale_fill_manual(<br>    values = c(&quot;#08306B&quot;, &quot;#4292C6&quot;,&quot;#C6DBEF&quot;,&quot;#666666&quot;), <br>    breaks = c(&quot;3&quot;,&quot;2&quot;,&quot;1&quot;,&quot;NA&quot;), <br>    labels = c(&quot;High&quot;,&quot;Medium&quot;,&quot;Low&quot;,&quot;NA&quot;))</pre><p>Since we want to customize map colors, we use scale_fill_manual instead. First, we define the four colors we want for the three levels and NA with values = c(). Then, we define which category correspond to the colors with breaks = c(). labels = c() sets the labels of the categories.</p><p>The rest of lines are the same as the first map.</p><p>Now go ahead and enjoy making your maps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a87e4fa602" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>