{"id":104,"date":"2014-02-15T20:41:41","date_gmt":"2014-02-15T20:41:41","guid":{"rendered":"http:\/\/kktg.net\/sgr\/?page_id=104"},"modified":"2017-02-24T10:35:08","modified_gmt":"2017-02-24T15:35:08","slug":"sgr-code-3","status":"publish","type":"page","link":"http:\/\/kktg.net\/sgr\/sgr-code-2\/sgr-code-3\/","title":{"rendered":"SGR Code from Chapters 12-13"},"content":{"rendered":"<h3>R Code for Chapter 12: Graphics I &#8212; The Basic Plots<\/h3>\n<pre lang=\"r-script\" line=\"1\">\r\n#===============================================================================\r\n# Chapter 12 - R Graphics I - Basic Plots\r\n#===============================================================================\r\n\r\n# Some data on democracy and corruption\r\n#\r\n# cGDP is per capita GDP. This data comes from the World Bank\r\n#\r\n# The CPI is a measure of the perception of corruption. 0 is highly corrupt\r\n# and 10 is very low corruption.  This widely used, if still controversial,\r\n# measure comes from the NGO Transparency International \r\n# (www.transparencyinternattional.org). This is the 2010 series.\r\n# \r\n# P4 is from the Polity IV dataset. It is the \"polity\" score which is a widely \r\n# used measure of political regime type.  It runs from -10, which is fully \r\n# autocracy to +10 which is fully democratic. You can read more about this data\r\n# at http:\/\/www.systemicpeace.org\/polity\/polity4.htm. The data is available at\r\n# http:\/\/www.systemicpeace.org\/inscr\/inscr.htm. This is the 2009 data.\r\n#\r\n# As with much real world data, there are several missing cases for each series.\r\n#\r\n\r\n\r\n# Data setup and housekeeping\r\n\r\n# Download and setup dataframe\r\n\r\nmyData = read.delim(file = \"http:\/\/www.kktg.net\/R\/Chapter12Data.txt\",\r\n  colClasses = c(\"character\", \"numeric\", \"numeric\", \"numeric\"), header = T)\r\n\r\n# Create a categorical version of the dem\/polity data\r\nmyData$dem =                           # Dem if Polity >7 \r\n  ifelse(myData$P4 > 7, 1, 0)    \r\nmyData$corrupt =                       # Corrupt if CPI<4\r\n  ifelse(myData$CPI < 4, 1, 0) \r\nmyData$cGDPk = myData$cGDP\/1000        # Per capita GDP in 1000s\r\n\r\n# Remove all observations with missing data\r\nmyData = myData[!is.na(myData$CPI) &#038; !is.na(myData$P4),]\r\n\r\n# This is the code I used for creating the actual illustrations in the book. For\r\n# this purpose I needed to create  publication ready png files. Each of the plots  \r\n# is preceded by the code for opening and setting up an external png file with \r\n# the png() function. The png file is created when the dev.off() command runs\r\n# at the end of the plot. \r\n#\r\n# If you want to just create the plots in an R graphics window, or the RStudio \r\n# plot window, you can just isolate and run the actual graphics code between \r\n# the png() setup function and the dev.off() command. \r\n#\r\n# For saving all of the illustrations to external files, I created a \r\n# subdirectory, \"illustrations\", that attaches to whatever the working \r\n# directory is.\r\n\r\n# Create a subdirectory of the current working directory to hold the new plots\r\ndir.create(\"illustrations\")\r\n\r\n# 12.1 A simple scatterplot =============================================== 12.1\r\n\r\npng(filename = \"illustrations\/fig-12-1-scatterplot.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nplot(myData$P4, myData$CPI)            # What could be simpler than that?\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 12.2 Pairs plots ======================================================== 12.2\r\n\r\npng(filename = \"illustrations\/fig-12-2-pairs-plot.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npairs(myData[,-1])                     # Pairs plot w\/all num vars in data frame\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-3-pairs-plot2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npairs(myData[,c(2:4)])                 # Pairs plot w\/o binary vars\r\n\r\ndev.off()                              # Output png file\r\n\r\n\r\n# 12.3 Line plots ========================================================= 12.3\r\n\r\nmeanCPI = tapply(myData$CPI,           # Create a variable with the mean CPI\r\n  myData$P4,                           #  at each level of P4\r\n  mean)\r\n  \r\nPolity = as.numeric(                   # Create variable with P4 levels\r\n  row.names(meanCPI))                  #  using the row names from myMeans\r\n\r\npng(filename = \"illustrations\/fig-12-4-line-plot1.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nplot(Polity, meanCPI, type = \"l\")      # Basic line plot\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-5-line-plot2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nplot(Polity, meanCPI, type = \"o\")      # Line plot with points overlayed\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-6-line-plot3.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nplot(Polity, meanCPI, type = \"b\")      # Plot with lines between points\r\n\r\ndev.off()                              # Output png file\r\n\r\n\r\n# 12.4 Boxplots =========================================================== 12.4\r\n\r\npng(filename = \"illustrations\/fig-12-7-boxplot1.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .25, .25))         # Change margins for png graphs\r\n\r\nboxplot(myData[,3:4])                  # Boxplot (leaving out binary data)\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-8-boxplot2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n                                \r\npar(mai = c(.5, .5, .25, .25))         # Change margins for png graphs\r\n\r\nboxplot(myData$CPI ~ myData$P4)        # Boxplot of CPI by Polity score\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-9-boxplot3.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .25, .25))         # Change margins for png graphs\r\n\r\nboxplot(myData$CPI ~                   # Boxplot of CPI by\r\n  cut(myData$P4,                       # Polity score cut into 4\r\n    quantile(myData$P4),               #  quartiles w\/ equal num of obs\r\n    include.lowest = T))               # Include lowest value in split\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 12.5 Histograms and bar charts ========================================== 12.5\r\n\r\npng(filename = \"illustrations\/fig-12-10-histogram1.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nhist(myData$P4, main = NA)             # Histogram of polity data\r\n\r\ndev.off()                              # Output png file\r\n\r\npng(filename = \"illustrations\/fig-12-11-density plot.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Change margins for png graphs\r\n\r\nplot(density(myData$P4), main = NA)    # Kernel density plot of polity data\r\n\r\ndev.off()                              # Output png file\r\n\r\n# barplots ---------------------------------------------------------------------\r\n\r\nP4breaks = cut(myData$P4, breaks = 5)  # Create factor with P4 in 5 bins\r\nnewP4 = tapply(myData$P4,              # Create vector of bar heights\r\n  P4breaks,                            #  based on the bins we created       \r\n  length)                              #  count number of obs in each bin\r\n\r\npng(filename = \"illustrations\/fig-12-12-barplot1.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .25, .25))         # Change margins for png graphs\r\n\r\nbarplot(newP4)                         # Create a barplot\r\n\r\ndev.off()                              # Output png file\r\n\r\nCPIbreaks = cut(myData$CPI, \r\n  breaks = 5)                          # Create factor with P4 in 5 bins\r\nnewCPI = tapply(myData$CPI,            # Create vector of bar heights\r\n  CPIbreaks,                           #  based on the bins we created       \r\n  length)                              #  count number of obs in each bin\r\n\r\npng(filename = \"illustrations\/fig-12-13-barplot2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n                                       \r\npar(mai = c(.5, 1, .25, .25))          # Change margins for png graphs\r\n\r\nbarplot(newCPI,                        # Create a barplot\r\n  horiz = T,                           # Rotate to horizontal\r\n  ylab = \"CPI Corruption Score\")       # Add y-axis label\r\n\r\ndev.off()                              # Output png file\r\n\r\n\r\n# 12.6 Dot plots ========================================================== 12.6\r\n\r\n# Create a basic dotchart of the corruption data\r\n\r\nCPIcounts = tapply(myData$CPI,         # Aggregate CPI data\r\n  as.factor(round(myData$CPI)),        #  in bins based on integer values\r\n  length)                              #  count number of obs in each bin     \r\n\r\npng(filename = \"illustrations\/fig-12-14-dotplot.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4))                         # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .25, .25))         # Change margins for png graphs\r\n\r\ndotchart(CPIcounts)                    # Produce basic dot chart\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 12.7 Pie charts ========================================================= 12.7\r\n\r\nCPIbreaks = cut(myData$CPI,            # Create factor dividing CPI data\r\n  c(0, 3.3, 6.6, 10))                  #  into 3 bins    \r\n\r\nCPIcounts = tapply(myData$CPI,         # Create vector of bar heights\r\n  CPIbreaks,                           #  based on the bins we created       \r\n  length)                              #  counting num of obs in each bin\r\n\r\nnames(CPIcounts) = paste(              # Create labels by pasting\r\n  c(\"High\",                            #   low\/medium\/high text     \r\n    \"Medium\",\r\n    \"Low\"),\r\n  names(CPIcounts),                    #   to existing bin labels\r\n  sep = \"--\")                          #   separated by \"--\"\r\n\r\npng(filename = \"illustrations\/fig-12-15-piechart-BW.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4))                         # Height at 4 inches\r\n\r\npar(mai = c(.25, .25, .75, .25))       # Change margins for pie chart\r\n\r\npie(CPIcounts,                         # Create a pie chart w\/CPI shares\r\n  col = c(\"white\", \"gray\", \"darkgray\"),# Set colors\r\n  main = \"Corruption\")                 # Add a title\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 12.8 Mosaic Plots ======================================================= 12.8\r\n# There are two steps here.  First we have to transform the data into a\r\n# contingency table.  This is an array that shows the frequency of observations\r\n# at each combination of the variables of interest.\r\n\r\n# A simple 2x2 table\r\n\r\nmyTable = table(                       # Create a contingency table\r\n  myData$dem,                          #   with x = dem\/not dem\r\n  myData$corrupt)                      #   and y = corrupt\/not corrupt\r\n\r\nmyTable                                # Display contingency table\r\n\r\npng(filename = \"illustrations\/fig-12-16-mosaicplot1.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .5, .25))          # Change margins for png graphs\r\n\r\n\r\nmosaicplot(myTable,                    # Create mosaic plot for myTable    \r\n  main = \"Democracy &#038; Corruption\",     # Set main title\r\n  xlab = \"Dem\",                        # Set x axis label\r\n  ylab = \"Corrupt\")                    # Set y axis label\r\n\r\ndev.off()                              # Output png file\r\n\r\n# A little more complex 10x4 table\r\n\r\nmyTable2 = table(                      # Create a contingency table\r\n  cut(myData$P4,                       #   with x = polity score\r\n    quantile(myData$P4)),              #   cut into quantiles (i.e. same num     \r\n                                       #   of observations in each group)\r\n  round(myData$CPI, 0))                #   and y = rounded CPI score.\r\n\r\nmyTable2                               # Display contingency table\r\n\r\npng(filename = \"illustrations\/fig-12-17-mosaicplot2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.5, .5, .3, .25))          # Change margins for png graphs\r\n\r\nmosaicplot(myTable2,                   # Create mosaic plot for myTable2\r\n  main = NA,                           # Turn off default plot title\r\n  xlab = \"PolityIV\",                   # Set x axis label\r\n  ylab = \"CPI 0=most corrupt\")         # Set y axis label\r\n\r\ndev.off()                              # Output png file\r\n\r\n<\/pre>\n<h3>R Code for Chapter 13: Graphics II -- The Boring Stuff<\/h3>\n<pre lang=\"r-script\" line=\"1\">\r\n#===============================================================================\r\n# Chapter 13 -- R Graphics II - Customization - The boring stuff\r\n#===============================================================================\r\n# This chapter provides the sometimes boring background foundation for \r\n# customizing R graphic output.\r\n#\r\n# 13.1 The graphics device ================================================ 13.1\r\n\r\n# 13.1a Screen-based devices ============================================= 13.1a\r\n#Simple plot examples\r\nmyX = seq(1:10)                        # Some x values\r\nmyY = c(1, 3, 2, 2, 4, 8, 7, 1, 8, 10) # Some y values\r\n\r\n# An onscreen window\r\nwindows()                              # Open graphics window\r\nplot(myX, myY)                         # plot myX and myY\r\nbringToTop()                           # Bring graphics window to front\r\ndev.off()                              # Close graphics window\r\n\r\n# 13.1b Raster\/bitmap devices ============================================ 13.1b  \r\n#  A png file\r\npng(filename = \"myPlot300.png\",        # Set filename for png output\r\n  bg = \"light gray\",                   # Set background to light gray\r\n  units = \"in\",                        # Set units to inches\r\n  res = 300,                           # Set resolution to 300dpi\r\n  height = 4,                          # Set height to 4 inches\r\n  width = 6,                           # Set width to 6 inches\r\n  pointsize = 12)                      # Set default pointsize to 12\r\n\r\nplot(myX, myY)                         # plot myX and myY\r\ndev.off()                              # Close graphics device\r\n\r\n# 13.1c Vector-based devices ============================================= 13.1c  \r\n# Postscript printing\r\npostscript(file = \"fig3.eps\",          # create EPS file\r\n  horizontal = FALSE,                  # don't rotate to landscape\r\n  bg = \"white\",                        # white background\r\n  onefile = FALSE,                     # One picture per file, \r\n  paper = \"special\",                   # paper size =pic size\r\n  width = 4.5, height = 3,             # set image size \r\n  pointsize = 10)                      # set font size \r\n  \r\nplot(myX, myY)                         # plot myX and myY\r\ndev.off()                              # Close graphics device\r\n\r\n# PDF output - multiple files\r\npdf(file = \"MyGraphs%02d.pdf\",         # Set up PDF files for output\r\n  onefile = FALSE,                     # Use one file per plot\r\n  family = \"Palatino\",                 # Set default font to Palatino\r\n  paper = \"letter\")                    # Set paper size\r\n\r\nplot(x = c(1:10), y = log(c(1:10)))    # Create a plot\r\nplot(x = c(1:100), y = log(c(1:100)))  # Create another plot\r\n\r\ndev.off()                              # Output and close device\r\n\r\n\r\n# PDF fonts - single file\r\n# This code prints out the set of built-in PDF fonts\r\n\r\npdf(file = \"illustrations\/fig-13-1-PDF-fonts.pdf\", \r\n  family = \"Palatino\",                 # Set default font to Palatino\r\n  paper = \"letter\")                    # Set paper size\r\n\r\nplot.new()                             # Start new plot\r\ntext(x = .5, y = .8,                   # Add text in the middle of the plot\r\n  \"AvantGarde\",                        # Text to print \r\n  family = \"AvantGarde\",               # Use AvantGarde font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .7,                   # Add text in the middle of the plot\r\n  \"Bookman\",                           # Text to print \r\n  family = \"Bookman\",                  # Use Bookman font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .6,                   # Add text in the middle of the plot\r\n  \"Courier\",                           # Text to print \r\n  family = \"Courier\",                  # Use Courier font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .5,                   # Add text in the middle of the plot\r\n  \"Helvetica\",                         # Text to print \r\n  family = \"Helvetica\",                # Use Helvetica font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .4,                   # Add text in the middle of the plot\r\n  \"Helvetica-Narrow\",                  # Text to print \r\n  family = \"Helvetica-Narrow\",         # Use Helvetica-Narrow font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .3,                   # Add text in the middle of the plot\r\n  \"NewCenturySchoolbook\",              # Text to print \r\n  family = \"NewCenturySchoolbook\",     # Use NewCenturySchoolbook font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .2,                   # Add text in the middle of the plot\r\n  \"Palatino\",                          # Text to print \r\n  family = \"Palatino\",                 # Use Palatino font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ntext(x = .5, y = .1,                   # Add text in the middle of the plot\r\n  \"Times\",                             # Text to print \r\n  family = \"Times\",                    # Use Times font\r\n  cex = 2)                             # Set fontsize to 2\r\n\r\ndev.off()                              # Output and close device\r\n\r\n# 13.3 The plot layout ==================================================== 13.3\r\n# The plot area and margins\r\n\r\nmyX = seq(1:10)                        # Some x values\r\nmyY = c(1, 3, 2, 2, 4, 8, 7, 1, 8, 10) # Some y values\r\n\r\n# Plot, region, and device areas\r\n\r\npng(filename = \"illustrations\/fig-13-2-plot regions-BW.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(omi = c(.5, .5, .5, .5),           # Set outer margin at .5 inches\r\n  mai = c(.8, .8, .8, .8),             # Set inner margin btwn figure & plot\r\n  fin = c(4.5, 2.5))                   # Set the plot at 4.5 x 2.5 inches\r\n\r\nplot(myX, myY)                         # Start new plot in device window\r\nbox(\"outer\",                           # Create a box on outer margin\r\n  col = \"darkgray\", lwd = 6)           #   with a thick dark gray line\r\nbox(\"inner\", col = \"black\", lty = 2)   # Dashed line for figure region (inner)\r\nbox(\"figure\", col = \"black\", lwd = 4)  # Black line for figure region (figure)\r\nbox(\"plot\", col = \"black\")             # Thin black line for plot region (plot)\r\nmtext('Device Region: omi = .5\"',      # Put text in margin of device region\r\n  line = 1, outer = TRUE)              #   indicating the outer margin\r\nmtext('Figure Region: mai = .8\"',      # Put text in the figure margin\r\n  line = 2)                            #   on the 2nd line\r\ntext(x = 5, y = 5, \"Plot Region\")      # Place text in center of plot region\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 13.4 Graphic coordinates ================================================ 13.4\r\n\r\n# Regular x,y coordinates\r\nmyX = c(0:20)                          # Create x var that runs 0 to 20\r\nmyY = myX * .5                         # Create y var that runs 0 to 10\r\n\r\npng(filename = \"illustrations\/fig-13-3-placed objects.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Plot margins - no title\r\n\r\nplot(myX, myY, type = \"n\")             # Plot x & y, but suppress points\r\ntext(x = 15, y = 6, \"Hello World!\")    # Add text at x = 15 and y = 6\r\npolygon(x = c(7, 15, 15, 7),           # Add a rectangle at x coords\r\n  y = c(1, 1, 3, 3))                   #   and y coords\r\npoints(x = c(5, 18), y = c(6, 1),      # Add a dashed line between points \r\n  type = \"l\", lty = 2)                 #  at given x and y coordinates.     \r\n\r\nxtext = \"x coordinates 0-20\"           # Some text for adding to plot\r\nytext = \"y coordinates 0-10\"           # Some more text for plot    \r\n\r\narrows(x0 = 6, y0 = 8, x1 = 0,         # Add a horizontal arrow\r\n  lwd = 2)                             #   Set line width to 2\r\ntext(x = 10, y = 8, xtext)             # Add coordinates text\r\narrows(x0 = 14, y0 = 8, x1 = 20,       # Add another horizontal arrow\r\n  lwd = 2)                             # Set line width to 2\r\n\r\narrows(x0 = 4, y0 = 2, y1 = 0,         # Add a vertical arrow\r\n  lwd = 2)                             # Set line width to 2\r\ntext(x = 4, y = 5, ytext, srt = 90)    # Add rotated y coordinates text\r\narrows(x0 = 4, y0 = 8, y1 = 10,        # Add another vertical arrow\r\n  lwd = 2)                             # Set line width to 2\r\n\r\ndev.off()                              # Output png\r\n\r\n# Proportional coordinates\r\n\r\npar()$usr                              # Show usr coords from previous plot\r\n\r\npng(filename = \"illustrations\/fig-13-4-usr coords.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Plot margins - no title\r\n\r\nplot(myX, myY, type = \"n\")             # Plot x & y, but suppress points\r\npar(usr = c(0, 1, 0, 1))               # Set coordinates based on % of plot area\r\ntext(.5, .5, \"Hello World!\")           # Place text in middle of plot\r\npolygon(x = c(.25, .75, .75, .25),     # Place box at 25% from edges\r\n  y = c(.25, .25, .75, .75),\r\n  lwd = 4)                             # Set the line width at 4\r\n\r\nxtext2 = \"x coordinates 0-1\"           # Some text for adding to plot\r\nytext2 = \"y coordinates 0-1\"           # Some more text for plot    \r\n\r\narrows(x0 = .35, y0 = .8, x1 = 0,      # Add a horizontal arrow\r\n  lwd = 2)                             # Set line width to 2\r\ntext(x = .5, y = .8, xtext2)           # Add coordinates text\r\narrows(x0 = .65, y0 = .8, x1 = 1,      # Add another horizontal arrow\r\n  lwd = 2)                             # Set line width to 2\r\n\r\narrows(x0 = .2, y0 = .2, y1 = 0,       # Add a vertical arrow\r\n  lwd = 2)                             # Set line width to 2\r\ntext(x = .2, y = .5, ytext2, srt = 90) # Add rotated y coordinates text\r\narrows(x0 = .2, y0 = .8, y1 = 1,       # Add another vertical arrow\r\n  lwd = 2)                             # Set line width to 2\r\n\r\ndev.off()                              # Output png file\r\n\r\n# 13.5 Overlaying plots =================================================== 13.5\r\n\r\nmyX1 = c(1, 3, 4, 7, 9, 12, 15)\r\nmyY1 = c(15, 17, 14, 19, 24, 23, 24)\r\nmyY2 = c(8, 6, 3, 5, 4, 2, 1)\r\n\r\npng(filename = \"illustrations\/fig-13-5-overlay-BW.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(1, 1, .25, .25))           # Plot margins - no title\r\n\r\nplot(myX1, myY1,                       # Plot myX1 and myY1\r\n  ylim = c(0, 25),                     # Set Y axis range for both plots\r\n  type = \"l\",                          # Line plot\r\n  ylab = \"myY1 & myY2\")                # Set Y axis label\r\n\r\npar(new = T)                           # Overlay the next plot\r\nplot(myX1, myY2,                       # Plot myX1 and myY2\r\n  type = \"l\",                          # Line plot\r\n  lty = 2,                             # Set line type to dashes\r\n  axes = FALSE,                        # Turn off the axes\r\n  xlab = NA, ylab = NA)                # Turn off the labels\r\n\r\ndev.off()                              # Output png file\r\n\r\n\r\n\r\n# 13.6 Multiple plots ===================================================== 13.6\r\n                     \r\npng(filename = \"illustrations\/fig-13-6-mfrow.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\n# mfrow approach\r\npar(mfrow = c(1, 2))                   # Set mfrow for 1 row 2 columns\r\nplot.new()                             # New plot\r\nbox(\"plot\")                            # Draw box around plot area\r\nbox(\"fig\")                             # Figure area box\r\ntext(x = .5, y = .5,                   # Put text in middle of plot\r\n  labels = \"This is plot 1\",           #   identifying plot 1\r\n  cex = 1.5)                           # Set font size\r\n\r\nplot.new()                             # New plot\r\nbox(\"plot\")                            # Draw box around plot area\r\nbox(\"fig\")                             # Figure area box\r\ntext(x = .5, y = .5,                   # Put text in middle of plot\r\n  labels = \"This is plot 2\",           #   identifying plot 2\r\n  cex = 1.5)                           # Set font size\r\n\r\ndev.off()                              # Output png file\r\n\r\n# The layout Function ==========================================================\r\n# Some simple examples\r\nlayout(matrix(c(1:4), ncol = 2))       # A simple 2x2 grid using layout\r\nlayout.show(4)                         # Show the resulting grid\r\n\r\npng(filename = \"illustrations\/fig-13-7-layout method.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\nlayout(                                # Setup a multiplot layout\r\n  matrix(c(1:15),                      # Create a matrix of 15 cells\r\n    ncol = 3,                          #   in 3 columns (5 rows of 3 cells)\r\n    byrow = T),                        # Order the cells by row\r\n  heights = c(2, 2, .5, .5, 1))        # Set row heights\r\n\r\nlayout.show(15)                        # Show the layout grid\r\n\r\ndev.off()                              # Output png file\r\n\r\n# A more complex layout example ------------------------------------------------\r\n\r\npng(filename = \"illustrations\/fig-13-8-layout2.png\",\r\n  units = \"in\",                        # Set measurements in inches\r\n  res = 1200,                          # Set resolution at 1200dpi\r\n  width = 6,                           # Width at 6 inches\r\n  height = 4)                          # Height at 4 inches\r\n\r\npar(mai = c(.6, .6, .5, .1))           # Set margins around plots\r\n\r\nlayout(                                # Set up a multiplot layout\r\n  matrix(c(1, 1, 4, 2, 3, 4),          # Create a matrix of 6 cells\r\n    ncol = 3,                          #   in 3 columns (3 cells per row)\r\n    byrow = T),                        # Order the cells by row\r\n  heights = c(.6, .4),                 # Set row heights\r\n  widths = c(.34, .33, .33))           # Set column widths\r\n\r\nlayout.show(4)                         # Preview the layout grid\r\n\r\nmyX = c(0:10)                          # Some data for plots \r\nmyY = log(myX + 1) \r\nmyZ = c(30, 60)\r\n\r\n# Some plots to fill in layout\r\nplot(myX, myY, type = \"b\", main = \"Plot 1\")\r\npar(mai = c(.6, .6, .5, .1))           # Change plot margins\r\nplot(myX, myX^2, ylim = c(0, 100), type = \"o\", main = \"Plot 2\")\r\npar(mai = c(.6, .35, .5, .1))          # Change plot margins\r\nbarplot(myZ, ylim = c(0, 100), main = \"Plot 3\")\r\npar(mai = c(.6, .2, .5, .1))           # Change plot margins\r\ndotchart(10 - myX, main = \"Plot 4\")\r\n\r\ndev.off()                              # Output the png file\r\n\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>R Code for Chapter 12: Graphics I &#8212; The Basic Plots #=============================================================================== # Chapter 12 &#8211; R Graphics I &#8211; Basic Plots #=============================================================================== # Some data on democracy and corruption # # cGDP is per capita GDP. This data comes from the World Bank # # The CPI is a measure of the perception of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":98,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-104","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/pages\/104","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/comments?post=104"}],"version-history":[{"count":27,"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/pages\/104\/revisions"}],"predecessor-version":[{"id":590,"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/pages\/104\/revisions\/590"}],"up":[{"embeddable":true,"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/pages\/98"}],"wp:attachment":[{"href":"http:\/\/kktg.net\/sgr\/wp-json\/wp\/v2\/media?parent=104"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}