Lew - Week 3 Background a Plot Is Created in Base R Graphics by first Calling a High-Level Function That Creates a Complete Plot

Total Page:16

File Type:pdf, Size:1020Kb

Lew - Week 3 Background a Plot Is Created in Base R Graphics by first Calling a High-Level Function That Creates a Complete Plot R Graphics Statistics X410A - Spring 2014 - Lew - Week 3 Background A plot is created in base R graphics by first calling a high-level function that creates a complete plot Second, low-level functions to add more output to the plot (such as additional lines or points) Plots in R are created in layers like a cake. In RStudio, plots appear in the plot window (lower right hand corner) Basic Rules If there is only going to be one plot per page, then a high-level function is used to start a new plot on a new page. We can put multiple plots on a page: A high- level function is instructed to start the next plot on the same page, only starting a new page when the number of plots per page is exceeded. All low-level functions add output to the current plot only. plot( ) The most important high-level function in base R graphics is plot( ). plot( ) can take many arguments The first argument to plot( ) is data, such as a vector but it could be a data frame. The second argument can be data if a scatterplot is desired, but it can be nearly anything. R is quite flexible. Example Example Example Example Explanation In the first case, all of the data to plot are specified in a single data frame. The result is a scatter plot matrix - good for exploring. In the second case, a grouping variable such as Diet in a plot will yield a bar chart (bar plot) Third and Fourth cases look the same. Separate x and y variables are specified as two separate arguments (3rd). A formula of the form y ~ x, plus a data frame that contains the variables mentioned in the formula (4th). More Explanations The plot( ) function is generic therefore, the plot( ) function can cope with the same data being specified in several different formats (and it will produce the same result). However, the fact that plot( ) is generic also means that if plot( ) is given different types of data, plot( ) might produce different types of plots. Example Features R graphics does not make a big distinction between different types of plots. R just sees different types of plots as variations in the presentation of the data. For example, we do not need an entirely new command to have a line plot. We can modify options on a scatterplot. Example Additional Features R graphics also does not make a big distinction between a plot of a single set of data and a plot containing multiple series of data. Additional data series can be added to a plot using low-level functions such as points( ) or lines(). Example Type of Graphs R can make just about any type of plot. Some do not have names. Others we see often, such as histograms, kernel density plots, dot plots, bar charts (simple, stacked, grouped), line charts, pie charts (simple, annotated, 3D), boxplots (simple, notched, violin plots, bagplots) scatter plots (simple, with fit lines, scatterplot matrices, high density plots, and 3D plots). Customizing Plots Using the par( ) function we can examine the default graphical settings R lets us change nearly every one (there are over 100) but we will only examine a few commonly modified settings in detail today. Colors R has 657 built-in colors, many more can be created. There are 3 basic settings: col=, fg= and bg= col= is used for the colors of lines, symbols and text fg= specifies the colors of axes and borders, other arguments do this too bg= specifies the color of the background or fill Colors There are several specific settings such as col.main= for the plot title, col.axis = for the axis labels etc. Colors can be specified by number, name, hexadecimal, or RGB Color Example - Names Color by Number Color by RGB Colors in Action Line Type & Width lty= controls the appearance of lines on a plot, the values 1 through 6 are used lwd = controls line thickness, defaults to 1, and lwd=2 is interpreted as twice as thick. lwd=3 is three times and so forth. Line Type & Width Example Line Type & Width Example Fonts The settings family= and font= control drawing text on a plot. family= is a character value like “Gill Sans”, specific fonts must be installed on your operating system to work. Generic settings (work anywhere) are “serif”, “sans”, and “mono”. This affects text in the figure region. font= 1 normal, 2 bold, 3 italic, 4 bold - italic this affects text in the plot region. Family & Fonts Text Size ps= and cex= control the appearance of text on a graphic. ps= controls the absolute font size setting its default is 16 cex= is character expansion, it is a multiplier and its default is 1. The final font size specification is ps * cex. Data Symbols There are 25 basic symbols The pch= setting takes the values 0 through 25. See ?pch for more help pch= symbols 0 through 25 Example Titles You can add titles in the plot( ) OR You can use the title( ) function to add labels to a plot. Settings are: main="main title", sub="sub-title", xlab="x-axis label", ylab="y-axis label" and are the same whether you use plot( ) or title( ) Legend Legends are placed within the plot region in plot( ) A legend needs an x,y coordinate for placement, here we use the minimum of x and y=17. The annotation for the legend follows 3:5 for the number of gears. We specify multiple colors and symbols with c( ) Axes You can create custom axes using the axis( ) function. axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, ...) But you just might use plot( ) because it has the most important axes options (labeling the axis and setting its range of values) with xlab=, ylab=, xlim=, ylim= Break Here Please take a 10 minute break here There is an in class exercise if you want to keep working I will walk around and answer questions Common Stat Graphics Bar plot or Bar Chart Mosaic Plot Stem and Leaf Dot Plot or Stripchart Boxplot Histogram Bar Plot (Bar Chart) A bar plot displays the frequency (or relative frequency) for all observations of a categorical variable. Bar plots can be displayed vertically or horizontally Bar plots can be grouped or stacked Don’t confuse them with histograms (later) Example Mosaic Plot The mosaic plot is a graphical representation of the two-way frequency table or Contingency Table. A mosaic plot is divided into rectangles, so that the area of each rectangle is proportional to the proportions of the Y variable in each level of the X variable. Example Stem & Leaf Plot A stem-and-leaf display presents quantitative data in a graphical format, used to visual the shape of a distribution It is like a histogram Used exploratory data analysis for small datasets. Example Dot Plot or Stripchart A stripchart or dot plot is a one dimensional scatter plot. It is used for small datasets Use the stripchart function to create dot plots and stripcharts. Example Boxplot boxplot ( ) is used to depict groupings of numerical data through their five-number summaries. It will indicate which observations might be considered outliers. boxplots can be drawn horizontally or vertically. boxplot( ) can operate on a single vector of values, but usually two or more are better suited. Example Example Histograms The base R function hist( ) allows you draw histograms. The function truehist() from MASS is preferred. Both functions only need data (a vector) to produce a histogram By default hist() will use the range of the variable on the x-axis and frequency counts on the y-axis By default truehist() its vertical axis has a relative frequency density scale, so the product of the dimensions of any panel gives the relative frequency. Hence the total area under the histogram is 1 and it is directly comparable estimates of the probability density function. Example truehist() & low level functions Exporting Graphics PDF( ), JPEG( ), and PNG( ) are some of the possible graphic device choices that will save a graphic to your computer. They can take arguments which give instructions about the saved graphic (e.g., height and width) dev.off( ) is used to close the device and write the file. Export Example Break Here Please take a 10 minute break here There is an in class exercise if you want to keep working I will walk around and answer questions Basic Mapping R can map data It has a built in library of maps We can combine maps and other functions to produce some interesting geographic analyses The basic package is mapdata map example map example map example map example map example map example package Lattice "Trellis" or Lattice plots extend the usual kind of univariate and bivariate plots to situations where some categorical or factor may influence the distribution of the data. They do this by generating an array of simple plots arranged according to the values of some "conditioning" variables. Steps Call the library(lattice) Create or locate the factor which is used as a condition (use equal.count() for example). In lattice, it is known as a “shingle” Use one of the lattice plotting functions (use xyplot for example) Basic plot + map Conditioning Lattice Example Two “shingles” Layering it on Stacked Bar Chart Boxplot Dot plot Strip plot 3D plot.
Recommended publications
  • 2. Graphing Distributions
    2. Graphing Distributions A. Qualitative Variables B. Quantitative Variables 1. Stem and Leaf Displays 2. Histograms 3. Frequency Polygons 4. Box Plots 5. Bar Charts 6. Line Graphs 7. Dot Plots C. Exercises Graphing data is the first and often most important step in data analysis. In this day of computers, researchers all too often see only the results of complex computer analyses without ever taking a close look at the data themselves. This is all the more unfortunate because computers can create many types of graphs quickly and easily. This chapter covers some classic types of graphs such bar charts that were invented by William Playfair in the 18th century as well as graphs such as box plots invented by John Tukey in the 20th century. 65 by David M. Lane Prerequisites • Chapter 1: Variables Learning Objectives 1. Create a frequency table 2. Determine when pie charts are valuable and when they are not 3. Create and interpret bar charts 4. Identify common graphical mistakes When Apple Computer introduced the iMac computer in August 1998, the company wanted to learn whether the iMac was expanding Apple’s market share. Was the iMac just attracting previous Macintosh owners? Or was it purchased by newcomers to the computer market and by previous Windows users who were switching over? To find out, 500 iMac customers were interviewed. Each customer was categorized as a previous Macintosh owner, a previous Windows owner, or a new computer purchaser. This section examines graphical methods for displaying the results of the interviews. We’ll learn some general lessons about how to graph data that fall into a small number of categories.
    [Show full text]
  • Chapter 16.Tst
    Chapter 16 Statistical Quality Control- Prof. Dr. Samir Safi TRUE/FALSE. Write 'T' if the statement is true and 'F' if the statement is false. 1) Statistical process control uses regression and other forecasting tools to help control processes. 1) 2) It is impossible to develop a process that has zero variability. 2) 3) If all of the control points on a control chart lie between the UCL and the LCL, the process is always 3) in control. 4) An x-bar chart would be appropriate to monitor the number of defects in a production lot. 4) 5) The central limit theorem provides the statistical foundation for control charts. 5) 6) If we are tracking quality of performance for a class of students, we should plot the individual 6) grades on an x-bar chart, and the pass/fail result on a p-chart. 7) A p-chart could be used to monitor the average weight of cereal boxes. 7) 8) If we are attempting to control the diameter of bowling bowls, we will find a p-chart to be quite 8) helpful. 9) A c-chart would be appropriate to monitor the number of weld defects on the steel plates of a 9) ship's hull. MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Which of the following is not a popular definition of quality? 1) A) Quality is fitness for use. B) Quality is the totality of features and characteristics of a product or service that bears on its ability to satisfy stated or implied needs.
    [Show full text]
  • Section 2.2: Bar Charts and Pie Charts
    Section 2.2: Bar Charts and Pie Charts 1 Raw Data is Ugly Graphical representations of data always look pretty in newspapers, magazines and books. What you haven’tseen is the blood, sweat and tears that it some- times takes to get those results. http://seatgeek.com/blog/mlb/5-useful-charts-for-baseball-fans-mlb-ticket-prices- by-day-time 1 Google listing for Ru San’sKennesaw location 2 The previous examples are informative graphical displays of data. They all started life as bland data sets. 2 Bar Charts Bar charts are a visual way to organize data. The height or length of a bar rep- resents the number of points of data (frequency distribution) in a particular category. One can also let the bar represent the percentage of data (relative frequency distribution) in a category. Example 1 From (http://vgsales.wikia.com/wiki/Halo) consider the sales …g- ures for Microsoft’s videogame franchise, Halo. Here is the raw data. Year Game Units Sold (in millions) 2001 Halo: Combat Evolved 5.5 2004 Halo 2 8 2007 Halo 3 12.06 2009 Halo Wars 2.54 2009 Halo 3: ODST 6.32 2010 Halo: Reach 9.76 2011 Halo: Combat Evolved Anniversary 2.37 2012 Halo 4 9.52 2014 Halo: The Master Chief Collection 2.61 2015 Halo 5 5 Let’s construct a bar chart based on units sold. Translating frequencies into relative frequencies is an easy process. A rela- tive frequency is the frequency divided by total number of data points. Example 2 Create a relative frequency chart for Halo games.
    [Show full text]
  • Bar Charts and Box Plots Normal Poisson Exponential Creating a Simple Yet Effective Plot Requires an 02468 C 1.0 Exponential Uniform Understanding of Data and Tasks
    THIS MONTH a Uniform POINTS OF VIEW Normal Poisson Exponential 02468 b Uniform Bar charts and box plots Normal Poisson Exponential Creating a simple yet effective plot requires an 02468 c 1.0 Exponential Uniform understanding of data and tasks. λ = 1 Min = 5.5 Normal Max = 6.5 0.5 Poisson σμ= 1, = 5 μ = 2 Bar charts and box plots are omnipresent in the scientific literature. 0 02468 They are typically used to visualize quantities associated with a set of Figure 2 | Representation of four distributions with bar charts and box plots. items. Representing the data accurately, however, requires choosing (a) Bar chart showing sample means (n = 1,000) with standard-deviation the appropriate plot according to the nature of the data and the task at error bars. (b) Box plot (n = 1,000) with whiskers extending to ±1.5 × IQR. hand. Bar charts are appropriate for counts, whereas box plots should (c) Probability density functions of the distributions in a and b. λ, rate; be used to represent the characteristics of a distribution. µ, mean; σ, standard deviation. Bar charts encode quantities by length, which is a highly accurate visual encoding and preferred over the angle-based strategy used in to represent such uncertainty. However, because the bars always start pie charts (Fig. 1a). Often the counts that we want to represent are at zero, they can be misleading: for example, part of the range covered sums over multiple categories. There are several options to visualize by the bar might have never been observed in the sample.
    [Show full text]
  • Measurement & Transformations
    Chapter 3 Measurement & Transformations 3.1 Measurement Scales: Traditional Classifica- tion Statisticians call an attribute on which observations differ a variable. The type of unit on which a variable is measured is called a scale.Traditionally,statisticians talk of four types of measurement scales: (1) nominal,(2)ordinal,(3)interval, and (4) ratio. 3.1.1 Nominal Scales The word nominal is derived from nomen,theLatinwordforname.Nominal scales merely name differences and are used most often for qualitative variables in which observations are classified into discrete groups. The key attribute for anominalscaleisthatthereisnoinherentquantitativedifferenceamongthe categories. Sex, religion, and race are three classic nominal scales used in the behavioral sciences. Taxonomic categories (rodent, primate, canine) are nomi- nal scales in biology. Variables on a nominal scale are often called categorical variables. For the neuroscientist, the best criterion for determining whether a variable is on a nominal scale is the “plotting” criteria. If you plot a bar chart of, say, means for the groups and order the groups in any way possible without making the graph “stupid,” then the variable is nominal or categorical. For example, were the variable strains of mice, then the order of the means is not material. Hence, “strain” is nominal or categorical. On the other hand, if the groups were 0 mgs, 10mgs, and 15 mgs of active drug, then having a bar chart with 15 mgs first, then 0 mgs, and finally 10 mgs is stupid. Here “milligrams of drug” is not anominalorcategoricalvariable. 1 CHAPTER 3. MEASUREMENT & TRANSFORMATIONS 2 3.1.2 Ordinal Scales Ordinal scales rank-order observations.
    [Show full text]
  • Chapter 6 Presenting Your Data in Graphic Form Political Orientations
    UNIVARIATE ANALYSIS Chapter 6 Presenting Your Data in Graphic Form Political Orientations Now let’s turn our attention from religion to politics. Some people feel so strongly about politics that they joke about it being a religion. The General Social Survey distribute(GSS) data set has several items that reflect political issues. Two are key political items: POLVIEWS and PARTYID. These items will be the primary focus in this chapter. In the process of examining these variables, we are going to learn not only more about the politicalor orientations of respon- dents to the 2012 GSS but also how to use SPSS Statistics to produce and interpret data in graphic form. You will recall that in the previous chapter, we focused on a variety of ways of displaying univariate distributions (frequency tables) and summarizing them (measures of central ten- dency and dispersion). In this chapter, we are going to build on that discussion by focusing on several ways of presenting your data graphically. We will begin by focusing on two charts thatpost, are useful for variables at the nominal and ordinal levels: bar charts and pie charts. We will then consider two graphs appropriate for interval/ratio variables: histograms and line charts. Graphing Data With Direct “Legacy” Dialogs SPSS Statistics gives us acopy, variety of ways to present data graphically. Clicking the Graphs option on the menu bar will give you three options for building charts: Chart Builder, Interactive, and Legacy Dialogs. These take you to two chart-building methods developed by SPSS over the past 20 years. Chart Builder is the most recent.
    [Show full text]
  • Stacked Bar Charts……………………………………………12
    Effective Use of Bar Charts Purpose This tool provides guidelines and tips on how to effectively use bar charts to communicate research findings. Format This tool provides guidance on bar charts and their purposes, shows examples of preferred practices and practical tips for bar charts, and provides cautions and examples of misuse and poor use of bar charts and how to make corrections. Audience This tool is designed primarily for researchers from the Model Systems that are funded by the National Institute on Disability, Independent Living, and Rehabilitation Research (NIDILRR). The tool can be adapted by other NIDILRR-funded grantees and the general public. The contents of this tool were developed under a grant from the National Institute on Disability, Independent Living, and Rehabilitation Research (NIDILRR grant number 90DP0012-01-00). The contents of this fact sheet do not necessarily represent the policy of Department of Health and Human Services, and you should not assume endorsement by the Federal Government. 1 Overview and Organization Simple Bar Charts……………………………………..……....3 Clustered Bar Charts…………………………………………10 Stacked Bar Charts……………………………………………12 Paired Bar Charts…………………………………………..…14 Simple Bar Chart – Categorical Comparisons A bar chart is basically a vertical column chart oriented horizontally instead. Data values are displayed as horizontal bars. The magnitude of each data element is represented by the length of the bar. Can be used to display values for categorical items (diabetes prevalence by state, hospital performance rankings on a preferred clinical practice measure etc). Shows comparisons among the categorical groups on the measure. Categories displayed on the vertical axis. Simple Bar Chart – Categorical Comparisons Bar charts are preferred over column charts: When the categorical axis labels are lengthy; When you have 12 or more categories; When the metric to be displayed is duration (such as clinic lobby wait time per health center).
    [Show full text]
  • Which Chart Or Graph Is Right for You?
    Which chart or graph is right for you? Tracy Rodgers, Product Marketing Manager Robert Bloom, Tableau Engineer You’ve got data and you’ve got questions. You know there’s a chart or graph out there that will find the answer you’re looking for, but it’s not always easy knowing which one is best without some trial and error. This paper pairs appropriate charts with the type of data you’re analyzing and questions you want to answer. But it won’t stop there. Stranding your data in isolated, static graphs limits the number and depth of questions you can answer. Let your analysis become your organization’s centerpiece by using it to fuel exploration. Combine related charts. Add a map. Provide filters to dig deeper. The impact? Immediate business insight and answers to questions that actually drive decisions. So, which chart is right for you? Transforming data into an effective visualization (any kind of chart or graph) or dashboard is the first step towards making your data make an impact. Here are some best practices for conducting meaningful visual analysis: 2 Bar chart Bar charts are one of the most common data visualizations. With them, you can quickly highlight differences between categories, clearly show trends and outliers, and reveal historical highs and lows at a glance. Bar charts are especially effective when you have data that can be split into multiple categories. Use bar charts to: • Compare data across categories. Bar charts are best suited for data that can be split into several groups. For example, volume of shirts in different sizes, website traffic by referrer, and percent of spending by department.
    [Show full text]
  • Visualiation of Quantitative Information
    Visualisation of quantitative information Overview 1. Visualisation 2. Approaching data 3. Levels of measurement 4. Principals of graphing 5. Univariate graphs 6. Graphical integrity James Neill, 2011 2 Is Pivot a turning point for web exploration? (Gary Flake) (TED talk - 6 min. ) 4 Approaching Entering & data screening Approaching Exploring, describing, & data graphing Hypothesis testing 5 6 Describing & graphing data THE CHALLENGE: to find a meaningful, accurate way to depict the ‘true story’ of the data 7 Clearly report the data's main features 10 Levels of measurement • Nominal / Categorical • Ordinal • Interval • Ratio 12 Discrete vs. continuous Discrete - - - - - - - - - - Continuous ___________ Each level has the properties of the preceding 14 13 levels, plus something more! Categorical / nominal Ordinal / ranked scale • Conveys a category label • Conveys order , but not distance • (Arbitrary) assignment of #s to e.g. in a race, 1st, 2nd, 3rd, etc. or categories ranking of favourites or preferences e.g. Gender • No useful information, except as labels 15 16 Ordinal / ranked example: Ranked importance Interval scale Rank the following aspects of the university according to what is most • Conveys order & distance important to you (1 = most important • 0 is arbitrary through to 5 = least important) e.g., temperature (degrees C) __ Quality of the teaching and education • Usually treat as continuous for > 5 __ Quality of the social life intervals __ Quality of the campus __ Quality of the administration __ Quality of the university's reputation 17 18 Interval example: 8 point Likert scale Ratio scale • Conveys order & distance • Continuous, with a meaningful 0 point e.g. height, age, weight, time, number of times an event has occurred • Ratio statements can be made e.g.
    [Show full text]
  • Which Chart Or Graph Is Right for You? Tell Impactful Stories with Data
    Which chart or graph is right for you? Tell impactful stories with data Authors: Maila Hardin, Daniel Hom, Ross Perez, & Lori Williams January 2012 p2 You’ve got data and you’ve got questions. Creating a Interact with your data chart or graph links the two, but sometimes you’re not sure which type of chart will get the answer you seek. Once you see your data in a visualization, it inherently leads to more questions. Your bar graph reveals that This paper answers questions about how to select the sales tanked in the second quarter in the Southeast. best charts for the type of data you’re analyzing and the A scatter plot shows an unexpected concentration of questions you want to answer. But it won’t stop there. product defects in one category. Donations from older Stranding your data in isolated, static graphs limits the alumni are significantly down according to a heat map. number of questions you can answer. Let your data In each example, your reaction is the same: why? become the centerpiece of decision making by using it Equip yourself to answer these questions by making to tell a story. Combine related charts. Add a map. your visualization interactive. Doing so creates the Provide filters to dig deeper. The impact? Business opportunity for you and others to analyze your data insight and answers to questions at the speed of visually and in real-time, letting you answer questions Which chart or graph is right for you? Tell impactful stories with data Tell Which chart or graph is right for you? thought.
    [Show full text]
  • Bar Charts This Set of Notes Shows How to Construct a Bar Chart Using
    Revised July 2018 Bar Charts This set of notes shows how to construct a bar chart using Stata. It assumes that you have set Stata up on your computer (see the “Getting Started with Stata” handout), and that you have read in the set of data that you want to analyze (see the “Reading in Stata Format (.dta) Data Files” handout). In Stata, most tasks can be performed either by issuing commands within the “Stata command” window, or by using the menus. These notes illustrate both approaches, using the data file “GSS2016.DTA” (this data file is posted here: https://canvas.harvard.edu/courses/53958). Bar charts display differences in means for a quantitative variable across two or more groups, as opposed to histogram comparisons which display percentage distributions of a categorical variable within groups. For example, we can construct a bar chart of the mean hours per day of television viewing by self-attributed class: 1 Simple bar charts can be constructed easily via the Stata command line. The general command structure is graph bar <varname1>, over(<varname2>) where you enter a quantitative variable in place of “varname1" and a categorical variable in place of “varname2". Using the variables in the above graph, you would issue the command graph bar tvhours, over(class) This command produces a bare-bones graph with no enhancements. To enhance and improve the display, it is probably easier to use the Stata menus. For a bar chart, Click on “Graphics” Click on “Bar chart” When you do this, the “graph bar – Bar chart” window shown below opens up: 2 Under “Type of data” select “Graph of summary statistics.” Enter the name of your quantitative variable in the “Variable(s)” box in the middle of the window.
    [Show full text]
  • ١ Topics: Sources of Variation
    Islamic University, Gaza - Palestine Topics: • Control Charts for Variables • Some Special Difficulties of Estimating Indirect Costs in Economy Studies • Did it Pay to Use Statistical Quality Control? • Costs and Product Liability • SQC Techniques in Relation to certain Economic Aspects of Product liability • Control Charts for Variables Islamic University, Gaza - Palestine Sources of Variation • Variation exists in all processes. • Variation can be categorized as either; – Common or Random causes of variation, or • Random causes that we cannot identify • Unavoidable • e.g. slight differences in process variables like diameter, weight, service time, temperature Assignable causes of variation • Causes can be identified and eliminated • e.g. poor employee training, worn tool, machine needing repair ١ Islamic University, Gaza - Palestine Control charts identify variation • Chance causes - “common cause” – inherent to the process or random and not controllable – if only common cause present, the process is considered stable or “in control” • Assignable causes - “special cause” – variation due to outside influences – if present, the process is “out of control” Islamic University, Gaza - Palestine Control Charts for x and R Notation and values • Ri = range of the values in the ith sample Ri = xmax - xmin • R = average range for all m samples • is the true process mean • is the true process standard deviation ٢ Islamic University, Gaza - Palestine Control Charts for Xbar and R Statistical Basis of the Charts • Assume the quality characteristic
    [Show full text]