Scatter Plots


One very commonly used tool in exploratory analysis of multivariate data is the scatterplot. We will look at this in more detail later when we discuss regression and correlation. The R command for drawing a scatterplot of two variables is a simple command of the form "plot(x,y)."

> plot(airquality$Temp, airquality$Ozone)   # How do Ozone and temperature measurements relate?

 

With more than two variables, the pairs() command draws a scatterplot matrix.


Write the following command in R and describe what you see in terms of relationships between the variables.

> pairs(airquality[,1:4])

The default plotting symbols in R are not always pretty! You can actually change the plotting symbols, or colors to something nicer. For example, the following command

> plot(airquality$Temp, airquality$Ozone, col="red", pch =19)

repeats the scatterplot, this time with red filled circles that are nicer to look at. "col" refers to the color of symbols plotted. The full range of point plotting symbols used in R are given by "pch" in the range 1 to 25; see the help on "points" to see what each of these represent.

 

Scatterplots in R (R Tutorial 2.6) MarinStatsLectures [Contents]

  alternative accessible content

 

Modifying Plots in R (R Tutorial 2.8) MarinStatsLectures [Contents]

alternative accessible content Learn how to modify plots produced in R to change from the default values. You will learn to use commands such as "plot", "cex", "pch", "axis", "par", "mfrow", "col" and many more.

Adding Text to Plots in R (R Tutorial 2.9) MarinStatsLectures [Contents]

alternative accessible content

 

Stem and Leaf Plots


A neat way to summarize data that could just as easily be put in a histogram is to use a stem-and-leaf plot (compare to a histogram):

> stem(rnorm(40,100))

 

  The decimal point is 1 digit(s) to the right of the |

 

   97 | 7

   98 |

   98 | 5669

   99 | 00224

   99 | 58

  100 | 00111111122233

  100 | 55567889

  101 | 014

  101 | 6

  102 | 01

Note that the command rnorm(40,100) that generated these data is a standard R command that generates 40 random normal variables with mean 100 and variance 1 (by default). For more information, use the help function. Type ?rnorm to see the options for this command.

 

Stem and Leaf Plots in R (R Tutorial 2.4) MarinStatsLectures [Contents]

alternative accessible content

Summary Statistics for Groups


When dealing with grouped data, you will often want to have various summary statistics computed within groups; for example, a table of means and standard deviations. This can be done using the tapply() command. For example, we might want to compute the mean temperatures in each month: 

> tapply(airquality$Temp, airquality$Month, mean)

       5        6        7        8        9

65.54839 79.10000 83.90323 83.96774 76.90000

 

If there are any missing values, these can be excluded if we simply adding an extra argument na.rm=T to tapply.

Compute the range and mean of Ozone levels for each month, using the tapply command.

Graphics for Grouped Data


With grouped data, it is important to be able not only to create plots for each group but also to compare the plots between groups. We have already looked at examples with histograms and boxplots. As a further example, let us consider another data set esoph in R, relating to a case-control study of esophageal cancer in France, containing records for 88 age/alcohol/tobacco combinations. (Look up the R help on this data set to find out more about the variables.) The first 5 rows of the data are shown below:

 > esoph[1:5,]

  agegp     alcgp    tobgp ncases ncontrols

1 25-34 0-39g/day 0-9g/day      0        40

2 25-34 0-39g/day    10-19      0        10

3 25-34 0-39g/day    20-29      0         6

4 25-34 0-39g/day      30+      0         5

5 25-34     40-79 0-9g/day      0        27

 

We can draw a boxplot of the number of cancer cases according to each level of alcohol consumption (alcgp):

> boxplot(esoph$ncases ~ esoph$alcgp)

 

 We could also equivalently write:

> boxplot(ncases ~ alcgp, data = esoph)

 

Notation of the type y ~ x can be read as "y described using x". This is an example of a "model formula". We will encounter many more examples of model formulas later on- such as when we use R for regression analysis.

 

If the data set is small, sometimes a boxplot may not be very accurate, as the quartiles are not well estimated from the data and may give a falsely inflated or deflated figure. In those cases, plotting the raw data may be more desirable. This can be done using a strip chart. By hand, this is equivalent to a dot diagram where every number is marked with a dot on a number line.

 

What does the following command do?

 

> stripchart(ncases ~ agegp)

 

 

Detach the esoph data set and attach the air quality data set. Next, create the following plots in R, using the commands you have learnt above:

  1. Do a boxplot of ozone levels by month and wind speed by month.
  2. Do a strip chart of ozone levels by month.

 

 

Tables


Categorical data are often described in the form of tables. We now discuss how you can create tables from your data and calculate relative frequencies. The simple "table" command in R can be used to create one-, two- and multi-way tables from categorical data.  For the next few examples we will be using the dataset airquality.new.csv.  Here is a preview of the dataset:

 

  Ozone Solar.R Wind Temp Month Day goodtemp badozone

1    41     190  7.4   67     5   1      low      low

2    36     118  8.0   72     5   2      low      low

3    12     149 12.6   74     5   3      low      low

4    18     313 11.5   62     5   4      low      low

7    23     299  8.6   65     5   7      low      low

 

The columns good temp and badozone represent days when temperatures were greater than or equal to 80 (good) or not (low) and if the ozone was greater than or equal to 60 (high) or not (low), respectively. 

Read in the airquality.new.csv file and print out rows 50 to 60 of the new data set airquality.new.

 

Now, let us construct some simple tables. Make sure you first detach the air quality data set and attach airquality.new.

> table(goodtemp)

goodtemp

high  low

  54   57

 

> table(badozone)

 

> table(goodtemp, badozone)

 

> table(goodtemp, Month)

        Month

goodtemp  5  6  7  8  9

    high  1  4 24 15 10

    low  23  5  2  8 19

 

We can also construct tables with more than two sides in R. For example, what do you see when you do the following?

> table(goodtemp, Month, badozone)

 

As you add dimensions, you get more of these two-sided subtables and it becomes rather easy to lose track. This is where the ftable command is useful. This function creates "flat" tables; e.g., like this:

> ftable (goodtemp + badozone ~ Month)

      goodtemp high      low   

      badozone high low high low

Month                          

5                 0   1    1  22

6                 1   3    0   5

7                13  11    0   2

8                10   5    0   8

9                 4   6    0  19

 

It may sometimes be of interest to compute marginal tables; that is, the sums of the counts along one or the other dimension of a table, or relative frequencies, generally expressed as proportions of the row or column totals.

 

These can be done by means of the margin.table() and prop.table() functions respectively. For either of these, we first have to construct the original cross-table.

> Temp.month = table(goodtemp, Month)

> margin.table(Temp.month,1)    

## what does the second index (1 or 2) mean?

> margin.table(Temp.month,2)

> prop.table(Temp.month,2)

Graphical Display of Tables


For presentation purposes, it may be desirable to display a graph rather than a table of counts or percentages, with categorical data. One common way to do this is through a bar plot or bar chart, using the R command barplot. With a vector (or 1-way table), a bar plot can be simply constructed as:

> total.temp = margin.table(Temp.month,2)        

> barplot(total.temp)         ## what does this show?

 

If the argument is a matrix, then barplot creates by default a "stacked barplot", where the columns are partitioned according to the contributions from different rows of the table. If you want to place the row contributions beside each other instead, you can use the argument beside=T.

 

Construct a table of the "badozone" variable by month from the air quality data. Then create and interpret the bar plot you get using the following commands:

> ozone.month = table(badozone, Month)

> barplot(ozone.month)

> barplot(ozone.month, beside=T)

 

The bar plot by default appears in color; if you want a black-and-white illustration, you just need to add the argument col="white".          

 

Bar Charts and Pie Charts in R (R Tutorial 2.1) MarinStatsLectures [Contents]

alternative accessible content https://www.youtube.com/watch?v=Eph_Y0BmHU0&list=PLqzoL9-eJTNBDdKgJgJzaQcY6OXmsXAHU&index=13

Dot Charts and Pie Charts


Dot charts can be employed to study a table from both sides at the same time. They contain the same information as barplots with beside=T but give quite a different visual impression.

> dotchart(ozone.month)

 

Pie charts are generally not a good way to represent data because they are often used to make trivial data look impressive and are difficult to interpret They rarely contain information that would not have been at least as effectively conveyed in a bar plot. In R, they can be created using the pie() command, the argument being the same as that taken by barplot().

Saving and Exporting Figures in R


Click on the figure created in R so that the window is selected. Now click on "File" and "Save as"- you will see a number of options for file formats to save the file in. Common ones are PDF, png, jpeg, etc.. The "png" (portable network graphic) format is often the most compact, and is readable on different platforms and can be easily inserted into Word or PowerPoint documents.

There is also a direct "command-line" option to save figures as a file from R. The command varies according to file format, but the basic syntax is to open the file to save in, then create the plot, and finally close the file. For example,

 > png("barplotozone.png")          ## name the file to save the figure in

> barplot(ozone.month, beside=T)

> dev.off()                        ## close the plotting device

 

This option is often useful when you need to plot a large number of figures at once, and doing them one-by-one becomes cumbersome. There are also a number of ways to control the shape and size of the figure, look up the help on the figure plotting functions (e.g. "help(png)") for more details.

 

Summary:

(For some examples of 3D plots, see the posted R code 3d plots.R.)

 

Reading:

In particular note the abline() and legend() functions on page 72 (very useful!!), and section 12.4.2 and 12.5.1. You will need this for the homework.

 

Assignment: