Om grafieken te maken in R worden in RStudio scripts aangemaakt, die na “runnen” getoond worden in de “Console”en het “Plotscherm”. Daarmee (script & plot) lukt het niet om goed (effectief & efficient) te communiceren met mensen (publiek/lezers/kijkers). In R moeten de grafieken worden aangepast (grafische elementen) om te presenteren aan een publiek (van kijkers of lezers).
We gebruiken de interne dataset (in R) “mtcars” als voorbeeld.
Eerst de data verkennen:
library(knitr)
knitr::kable(
mtcars[1:32, 1:11], caption = "32 Auto's met 11 variabelen."
)
| mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |
| Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
| Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |
| Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
| Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |
| Valiant | 18.1 | 6 | 225.0 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 |
| Duster 360 | 14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 |
| Merc 240D | 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 |
| Merc 230 | 22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 |
| Merc 280 | 19.2 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.30 | 1 | 0 | 4 | 4 |
| Merc 280C | 17.8 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.90 | 1 | 0 | 4 | 4 |
| Merc 450SE | 16.4 | 8 | 275.8 | 180 | 3.07 | 4.070 | 17.40 | 0 | 0 | 3 | 3 |
| Merc 450SL | 17.3 | 8 | 275.8 | 180 | 3.07 | 3.730 | 17.60 | 0 | 0 | 3 | 3 |
| Merc 450SLC | 15.2 | 8 | 275.8 | 180 | 3.07 | 3.780 | 18.00 | 0 | 0 | 3 | 3 |
| Cadillac Fleetwood | 10.4 | 8 | 472.0 | 205 | 2.93 | 5.250 | 17.98 | 0 | 0 | 3 | 4 |
| Lincoln Continental | 10.4 | 8 | 460.0 | 215 | 3.00 | 5.424 | 17.82 | 0 | 0 | 3 | 4 |
| Chrysler Imperial | 14.7 | 8 | 440.0 | 230 | 3.23 | 5.345 | 17.42 | 0 | 0 | 3 | 4 |
| Fiat 128 | 32.4 | 4 | 78.7 | 66 | 4.08 | 2.200 | 19.47 | 1 | 1 | 4 | 1 |
| Honda Civic | 30.4 | 4 | 75.7 | 52 | 4.93 | 1.615 | 18.52 | 1 | 1 | 4 | 2 |
| Toyota Corolla | 33.9 | 4 | 71.1 | 65 | 4.22 | 1.835 | 19.90 | 1 | 1 | 4 | 1 |
| Toyota Corona | 21.5 | 4 | 120.1 | 97 | 3.70 | 2.465 | 20.01 | 1 | 0 | 3 | 1 |
| Dodge Challenger | 15.5 | 8 | 318.0 | 150 | 2.76 | 3.520 | 16.87 | 0 | 0 | 3 | 2 |
| AMC Javelin | 15.2 | 8 | 304.0 | 150 | 3.15 | 3.435 | 17.30 | 0 | 0 | 3 | 2 |
| Camaro Z28 | 13.3 | 8 | 350.0 | 245 | 3.73 | 3.840 | 15.41 | 0 | 0 | 3 | 4 |
| Pontiac Firebird | 19.2 | 8 | 400.0 | 175 | 3.08 | 3.845 | 17.05 | 0 | 0 | 3 | 2 |
| Fiat X1-9 | 27.3 | 4 | 79.0 | 66 | 4.08 | 1.935 | 18.90 | 1 | 1 | 4 | 1 |
| Porsche 914-2 | 26.0 | 4 | 120.3 | 91 | 4.43 | 2.140 | 16.70 | 0 | 1 | 5 | 2 |
| Lotus Europa | 30.4 | 4 | 95.1 | 113 | 3.77 | 1.513 | 16.90 | 1 | 1 | 5 | 2 |
| Ford Pantera L | 15.8 | 8 | 351.0 | 264 | 4.22 | 3.170 | 14.50 | 0 | 1 | 5 | 4 |
| Ferrari Dino | 19.7 | 6 | 145.0 | 175 | 3.62 | 2.770 | 15.50 | 0 | 1 | 5 | 6 |
| Maserati Bora | 15.0 | 8 | 301.0 | 335 | 3.54 | 3.570 | 14.60 | 0 | 1 | 5 | 8 |
| Volvo 142E | 21.4 | 4 | 121.0 | 109 | 4.11 | 2.780 | 18.60 | 1 | 1 | 4 | 2 |
summary(mtcars)
## mpg cyl disp hp
## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :6.000 Median :196.3 Median :123.0
## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
## drat wt qsec vs
## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
## Median :3.695 Median :3.325 Median :17.71 Median :0.0000
## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
## am gear carb
## Min. :0.0000 Min. :3.000 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
## Median :0.0000 Median :4.000 Median :2.000
## Mean :0.4062 Mean :3.688 Mean :2.812
## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
## Max. :1.0000 Max. :5.000 Max. :8.000
Vergelijkbaar met de functie summary() = fivenum() function: een “5-number summary”.
Dat is de Tukey’s vijf-cijferige samenvatting van invoergegevens. (John Wilder Tukey (1915-2000), Amerikaans statisticus).
# minimum, 1e kwartiel, mediaan, 3e kwartiel, maximum
fivenum(mtcars$mpg)
## [1] 10.40 15.35 19.20 22.80 33.90
fivenum(mtcars$wt)
## [1] 1.5130 2.5425 3.3250 3.6500 5.4240
Spreidingsdiagrammen zijn de werkpaarden van data-analyse en visualisatie.
Spreidingsdiagrammen of scatterplots zijn zeer geschikt om:
plot(mtcars$mpg~mtcars$wt) # Kale grafiek op basis van gegevens.
Figuur 1. Standaard spreidingsdiagram.
# Samenhang gewicht auto en aantal miles per gallon.
plot(mtcars$mpg~mtcars$wt,las= 1,frame=FALSE,ylim=c(10,35),xlim=c(1,6))
Figuur 2. Nu met horizontale labels, zonder plot frame en aangepaste x- en y-as.
par(mfrow=c(2,2),las=1)
plot(mtcars$mpg,type="n",main="a. Lege Plot")
plot(mtcars$mpg,type="p",main="b. Standaard")
plot(mtcars$mpg,type="b", main="c. Punten en lijnen")
plot(mtcars$mpg,type="h",main= "d. Verticale strepen")
Figuur 3 a, b, c en d. Weergave plot.
Aanpassingen om een plot meer “body” te geven, door het aantal toegepaste grafische eigenschappen uit te breiden en aan te passen.
par(mfrow=c(2,2),las=1)
plot(mtcars$mpg,type="l",main= "a. Alleen horizontale lijn")
plot(mtcars$mpg,type="o",main= "b. Overplotting")
# Kijk uit voor overplotting, onleesbaarheid ligt op de loer .
plot(mtcars$mpg,type="s", frame=FALSE,main="c. Trapsgewijs MPG") # stairs (trapsgewijs)
plot(mtcars$hp,type="S",frame=FALSE,main="d. Trapsgewijs HP") # stairs (trapsgewijs)
Figuur 4 a, b, c en d. Lijnsoorten.
Ook het frame rond de plot laat zich aanpassen. Maak een keuze welke type frame moet worden uitgevoerd voor de uiteindelijke “presentatieversie”.
par(mfrow=c(2,2),las=1)
plot(mtcars$mpg, bty = "o", main = "a. Standaard")
plot(mtcars$mpg, bty = "7", main = "b. bty = '7'")
plot(mtcars$mpg, bty = "L", main = "c. bty = 'L'")
plot(mtcars$mpg, bty = "U", main = "d. bty = 'U'")
Figuur 5 a, b, c en d. Framesoorten.
par(mfrow=c(2,2),las=1)
plot(mtcars$mpg, bty = "C", main = "a. bty = 'C'")
plot(mtcars$mpg, bty = "n", main = "b. bty = 'n'")
plot(mtcars$mpg, bty = "]", main = "c. bty = ']'")
Figuur 6 a, b en c. Framesoorten.
Een regressielijn geeft de samenhang tussen de variabelen op de x- en y-as weer ( “best fit” lijn).
Met “adj=0”, “adj=0,75” en “adj=1” plaats je de titel en de labels op hun specifieke positie ten opzicht van de assen (x en y).
par(las=1)
plot(mtcars$mpg~mtcars$wt,type="p",las=1,frame=FALSE,ylim=c(10,35),xlim=c(1,6),
xlab="Gewicht",ylab="MpG",main="Samenhang van Gewicht (x 1000 lbs) en Miles per Gallon.")
reg<-lm(mtcars$mpg~mtcars$wt)
abline (reg, col="red",lwd=2,lty=2)
Figuur 7. Regressielijn en de standaardpositie van titel en aslabels.
plot(mtcars$mpg~mtcars$wt,type="p",las=1,frame=FALSE,ylim=c(10,35),xlim=c(1,6),
xlab="Gewicht",ylab="MpG",main="Samengang van Gewicht (x 1000 lbs) en Miles per Gallon.",adj=0)
reg<-lm(mtcars$mpg~mtcars$wt)
abline (reg, col="red",lwd=2,lty=2)
Figuur 8. Regressielijn en de aangepaste positie van titel en aslabels met adj=0.
plot(mtcars$mpg~mtcars$wt,type="p",las=1,frame=FALSE,ylim=c(10,35),xlim=c(1,6),
xlab="Gewicht",ylab="MpG",main="Samenhang van Gewicht (x 1000 lbs) en Miles per Gallon.",adj=0.75)
reg<-lm(mtcars$mpg~mtcars$wt)
abline (reg, col="red",lwd=2,lty=2)
Figuur 9. Regressielijn en de aangepaste positie van titel en aslabels met adj=0.75.
plot(mtcars$mpg~mtcars$wt,type="p",las=1,frame=FALSE,ylim=c(10,35),xlim=c(1,6),
xlab="Gewicht",ylab="MpG",main="Regressie Gewicht (x 1000 lbs) en Miles per Gallon.",adj=1)
reg<-lm(mtcars$mpg~mtcars$wt)
abline (reg, col="red",lwd=2,lty=2)
Figuur 10. Regressielijn en de aangepaste positie van titel en aslabels met adj=1.
Elf variabelen (van de mtcars dataset) worden in een verzameling spreidingsdiagrammen weergegeven. Je ziet bijvoorbeeld dat “mpg” afgezet wordt tegen “cyl” en dit levert een indeling op van drie groepen auto’s met 4, 6 of 8 cylinders.
require(graphics)
pairs(mtcars, main = "mtcars data", gap = 1/2)
Figuur 11. Alle spreidingsdiagrammen in één weergave.
Gesorteerd op aantal cylinders zie je dat er drie verzamelingen onder worden geplaatst: aantal mijlen per gallon en het aantal paardenkrachten (horsepower). Met minder paardenkrachten meer mijlen per gallon (1 gallon= 4,546092 liter).
coplot(mpg ~ hp | as.factor(cyl), data = mtcars,
panel = panel.smooth, rows = 1)
Figuur 12. Correlatieplot (coplot).
Installeer het pakket: install.packages(“carData”) en gebruik de bibliotheek: library(car), dit pakket installeert een functie met onderdeel “scatterplot”.
library(car)
## Loading required package: carData
scatterplot(mpg~hp|cyl,data=mtcars,xlab="Pk",ylab="MpG",main="Uitgebreide Scatterplot")
Figuur 13. Uitgebreide scatterplot.
Ook op deze manier worden er drie groepen onderscheiden op basis van het aantal cylinders.
auteur <- c("©2021 Hans den Hartog")
kleurpaletTutorial<-c("#4b3b30","#5b473a",
"#6a5344","#896b58","#cfbfb4","#dfd4cd","#f1f2ed","#9fa09d","#767775","#4d4d4d")
par(mar=c(10,5,5,2),bg= "#cfbfb4", fg="#F1F2ED")
# met NULL worden de datapunten in de laag boven de eerste plot geplaatst,
# dan de 2e plot met points()
plot(NULL, xlim=c(1,6), ylim=c(0,35),las=1, adj=0,
main="Hoe zwaarder een auto, hoe minder miles a gallon.",cex.main=1.3,
font.main=2, col.main="#4B3B30",
xlab="Gewicht x 1000 lbs.\n(= 453,59 kg.)",
ylab="Miles per Gallon", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",
col.axis="#4B3B30",sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58")
# achtergrond grafiekframe : om die een aparte opmaak ten opzichte van de achtergrond te kunnen geven.
# usr A vector of the form c(x1, x2, y1, y2) giving the extremes of the user coordinates of the plotting region.
# When a logarithmic scale is in use (i.e., par("xlog") is true, see below),
# Then the x-limits will be 10 ^ par("usr")[1:2]. Similarly for the y-axis.
# Teken een rechthoek die samenvalt met het frame van de grafiek:
# rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "lightgray").
# met par("usr") haal je de gegevens van de plot op.
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col ="#DFD4CD80")
# grid lines
abline(h=0:35, col="#F1F2ED",lty=3)
abline(v=0:8, col="#F1F2ED",lty=3)
# regressielijn
abline(lm(mtcars$mpg ~ mtcars$wt),col="#4B3B30",lty=6,lwd=2)
#data points: met 80% transparantie
points(mtcars$mpg~mtcars$wt, col="#896B5880", pch=19, cex=1.6)
# de 2e plot over de 1e plot heen!
# toevoegen verklarende teksten
text("Regressielijn",x=4.7,y=7,col=c("#4B3B30"))
mtext("1 gallon (us) =. 3.7854 liter\n1 mile = 1,609 km.\n35 miles = 56,327 km.",
side=1,cex=0.8,line=4,adj=1,col=("#4b3b30"))
Figuur 14. Compleet (grafisch) aangepast spreidingsdiagram.
Een spreidingsdiagram met een titel als een krantenkop. Dit helpt de kijker/lezer op weg om de informatie die de figuur bevat eenvoudig te verwerven.
Twee soorten pinguïns worden hier vergeleken met elkaar. De verschillen in gewicht en flipperlengte worden weergegeven. Met de uitbreidingen van regressielijn en de lijnen met gemiddelde flipperlengte en bodymass worden er extra dimensies aan de grafiek toegevoegd. Hiermee wordt de op te nemen informatie beter toegankelijk gemaakt voor de waarnemer van deze afbeelding.
Figuur 15. Spreidingsdiagram(scatterplot) pinguïnsoorten.
Kloppen de volgende conclusies?
Figuur 16. Kleurenpalet in Adobe Kuler.
De gebruikte dataset is afkomstig van onderstaande website:
[https://allisonhorst.github.io/palmerpenguins/]
Figuur 17. Screenshot uit R script. Een poging om de “Heilige Graal” van The Grammar of Graphics te benaderen!
Uitgebreide info over "The Grammar of Graphics:
x <- c(1:10); y <- x; z <- 10/x
# marge(s)
par(mar=c(5, 4, 4, 8) + 4) # +4 vergroot de marges met 4
# plot x vs. y
plot(x, y,type="b", pch=21, col="red",
yaxt="n", lty=3, xlab="", ylab="")
# add x vs. 1/x
lines(x, z, type="b", pch=22, col="blue", lty=2)
# lijngrafiek met meerdere assen
axis(2, at=x,labels=x, col.axis="red", las=2)
axis(3,at=x,labels=x, col.axis="green", las=1)
# rechter as met kleinere letters en cijfers achter de komma.
axis(4, at=z,labels=round(z,digits=2), # twee cijfers achter de komma
col.axis="blue", las=2, cex.axis=0.7, tck=-.01) # plaatsing van"ticks".
Figuur 18.Standaardlijngrafiek met verschillende lijntypen, gekleurde labels en as-streepjes(tcks.Let ook op de marges (mar=c()) en de vergroting daarvan.
attach(USArrests)
#View(USArrests)
mr <- data.frame('moord' = USArrests$Murder, 'verkrachting' = USArrests$Rape)
sort_mr <- mr[order(-mr$verkrachting),]
collegenda <- c("red","blue")
plot(sort_mr$moord, type="o", pch = 16, xlim = c(0,55) ,ylim=c(0,50), las=1, adj=0,
col = c('red'),
xlab = "50 staten van Amerika", ylab = "Aantal misdrijven per 100000 inwoners",
main = "Nevada heeft veel geweld, North Dakota is relatief veilig " ,frame=FALSE)
lines(sort_mr$verkrachting, type="o", pch = 16, lty=1, col = c('blue') )
legend("topright", c("Moord","Verkrachting"), cex=0.8, fill=collegenda, bty = "n")
abline(h=7.788, col="Red", lty = 2, lwd=1)
abline(h=21.23, col="Blue", lty = 2, lwd=1)
text(x= 0, y= 20, label = "gemid. = 21.23", adj = 0, cex = 0.7)
text(x= 0, y= 6.5, label = "gemid. = 7.79", adj = 0, cex = 0.7)
text(x= 28, y= 25, label = "Mississippi", adj = 0, cex = 1)
text(x= 1, y= 49, label = "Nevada", adj = 0, cex = 1)
text(x= 47, y= 25, label = "North Dakota", adj = 0.6, cex = 1)
abline(v= 2.5, col="#ede7e3", lty = 2, lwd=1)
abline(v= 30, col="#ede7e3", lty = 2, lwd=1)
abline(v= 47, col="#ede7e3", lty = 2, lwd=1)
Figuur 19. Gesorteerd op type misdrijf: ‘verkrachting’.
source("http://www.openintro.org/stat/data/arbuthnot.R")
#View(arbuthnot)
dim(arbuthnot)# 82 records met 3 variabelen
## [1] 82 3
names(arbuthnot) # Welke naam hebben de variabelen
## [1] "year" "boys" "girls"
head(arbuthnot) # Toon de eerste zes records
arbuthnot # Toon alles
knitr::kable(
arbuthnot[1:82, 1:3], caption = "Jongens & Meisjes geboren in Londen tussen 1629-1710."
)
| year | boys | girls |
|---|---|---|
| 1629 | 5218 | 4683 |
| 1630 | 4858 | 4457 |
| 1631 | 4422 | 4102 |
| 1632 | 4994 | 4590 |
| 1633 | 5158 | 4839 |
| 1634 | 5035 | 4820 |
| 1635 | 5106 | 4928 |
| 1636 | 4917 | 4605 |
| 1637 | 4703 | 4457 |
| 1638 | 5359 | 4952 |
| 1639 | 5366 | 4784 |
| 1640 | 5518 | 5332 |
| 1641 | 5470 | 5200 |
| 1642 | 5460 | 4910 |
| 1643 | 4793 | 4617 |
| 1644 | 4107 | 3997 |
| 1645 | 4047 | 3919 |
| 1646 | 3768 | 3395 |
| 1647 | 3796 | 3536 |
| 1648 | 3363 | 3181 |
| 1649 | 3079 | 2746 |
| 1650 | 2890 | 2722 |
| 1651 | 3231 | 2840 |
| 1652 | 3220 | 2908 |
| 1653 | 3196 | 2959 |
| 1654 | 3441 | 3179 |
| 1655 | 3655 | 3349 |
| 1656 | 3668 | 3382 |
| 1657 | 3396 | 3289 |
| 1658 | 3157 | 3013 |
| 1659 | 3209 | 2781 |
| 1660 | 3724 | 3247 |
| 1661 | 4748 | 4107 |
| 1662 | 5216 | 4803 |
| 1663 | 5411 | 4881 |
| 1664 | 6041 | 5681 |
| 1665 | 5114 | 4858 |
| 1666 | 4678 | 4319 |
| 1667 | 5616 | 5322 |
| 1668 | 6073 | 5560 |
| 1669 | 6506 | 5829 |
| 1670 | 6278 | 5719 |
| 1671 | 6449 | 6061 |
| 1672 | 6443 | 6120 |
| 1673 | 6073 | 5822 |
| 1674 | 6113 | 5738 |
| 1675 | 6058 | 5717 |
| 1676 | 6552 | 5847 |
| 1677 | 6423 | 6203 |
| 1678 | 6568 | 6033 |
| 1679 | 6247 | 6041 |
| 1680 | 6548 | 6299 |
| 1681 | 6822 | 6533 |
| 1682 | 6909 | 6744 |
| 1683 | 7577 | 7158 |
| 1684 | 7575 | 7127 |
| 1685 | 7484 | 7246 |
| 1686 | 7575 | 7119 |
| 1687 | 7737 | 7214 |
| 1688 | 7487 | 7101 |
| 1689 | 7604 | 7167 |
| 1690 | 7909 | 7302 |
| 1691 | 7662 | 7392 |
| 1692 | 7602 | 7316 |
| 1693 | 7676 | 7483 |
| 1694 | 6985 | 6647 |
| 1695 | 7263 | 6713 |
| 1696 | 7632 | 7229 |
| 1697 | 8062 | 7767 |
| 1698 | 8426 | 7626 |
| 1699 | 7911 | 7452 |
| 1700 | 7578 | 7061 |
| 1701 | 8102 | 7514 |
| 1702 | 8031 | 7656 |
| 1703 | 7765 | 7683 |
| 1704 | 6113 | 5738 |
| 1705 | 8366 | 7779 |
| 1706 | 7952 | 7417 |
| 1707 | 8379 | 7687 |
| 1708 | 8239 | 7623 |
| 1709 | 7840 | 7380 |
| 1710 | 7640 | 7288 |
# Teken een lijngrafiek
par(bg = "#FFFFFF",fg="gray90", mar=c(5.5, 4.5, 4.5, 0)+4, col.lab="gray20",adj=1,cex=.5)
Aantal <- c(arbuthnot$year)
plot(Aantal,ylim=c(2500,8500),xaxt="n",xlab="Jaren",las=1, frame.plot=FALSE,
col.axis="gray30") #Teken eerst een plot(box)
# Dan de lijnen
lines(arbuthnot$girls,lwd=0.9,col="#EC6608")
lines(arbuthnot$boys,lwd=0.9,col="#2C5FC5")
# Plaats streepjes en labels op de xas. axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, ...)
# Side =1 = bottom, 2 = left, 3 = top, 4 = right)
# Dit werkt alleen als je de standaard x-as op "n" hebt gezet, zie boven xaxt="n"
axis(1, at = c(1,12,32,46,52,72,76,82), col.axis="gray30",
labels = c("1629","1640","1660","1674","1680","1700","1704","1710"),cex=.5)
axis(2,col.axis="gray30",las=1,col.lab="gray30",cex=.5)
# teken de vertikale lijnen op de speciale jaarplekken.
abline(v=1,lty="dotted",col = "gray90")
abline(v=12,lty="dotted",col = "gray90")
abline(v=32,lty="dotted",col = "gray90")
abline(v=52,lty="dotted",col = "gray90")
abline(v=72,lty="dotted",col = "gray90")
abline(v=82,lty="dotted",col = "gray90")
abline(v=76,lty="dotted",col="pink")
abline(v=46,lty="dotted",col="pink")
text(22,12000,"1639 - 1651 Engelse Burgeroorlog",col="gray50",cex=.9)
text(53,4000,"1666 Grote Brand van Londen", col ="gray50",cex=.9)
text(45,3750,"1665 Pestepidemie", col="gray50",cex=.9)
text(10,5750,"1630 Pestepidemie", col="gray50",cex=.9)
text(12,6000,"1632 Pestepidemie", col="gray50",cex=.9)
text(65,5500,"1674 en 1704 hebben een gelijke waarde,",col ="gray50",cex=.9)
text(65,5250,"waarschijnlijk fout in gegevens",col="gray50",cex=.9 )
text(82,8550,"Jongens",col ="#2C5FC5",cex=.9)
text(82,7100,"Meisjes",col="#EC6608",cex=.9)
title(main="In Londen geboren meisjes en jongens 1629 - 1710.\n(doopfeestgegevens)", col.main="gray50",adj=0,cex=.9)
# legenda vervalt bij "direct labeling" van de lijnen!!!!
# legend(52,4000,
# plaatst een legenda op de juiste plaats.
# c("Jongens","Meisjes"),
# plaatst tekst in de legenda, volgorde op basis van uiteinden van de lijnen!
# lty=c(1,1), # geeft de legenda de juiste symbolen of lijnen.
# lwd=c(2.5,2.5),col=c("#2C5FC5","#EC6608"), # gives the legend lines the correct color and width
#bty="n")
#plaats tekst linksonder op 3 lijnen beneden de x-as, met grootte 0.4 een maak blauw.
mtext("Bron: John Arbuthnot (1710)", side=1,line=3, cex=0.4, col="#2C5FC5", adj=0)
Figuur 20. Lijngrafiek met allerlei aanpassingen.
Steelbladdiagrammen worden gebruikt om verzamelingen gegevens grafisch weer te geven op een duidelijke, visuele manier (aantrekkelijk en overzichtelijk). In plaats van veel verschillende getallen in één lijst te hebben (zoals in een tabel), worden deze plots gebruikt om informatie uit een set te ordenen. De toepassing op vertrekschema’s van treinen en bussen is er een uit de echte wereld.
Figuur 21. Steelbladdiagram van een fictief reisschema: de uren zijn de “steel”, de “bladeren” de minuten, waarop een bus vertrekt.
stem(mtcars$wt)
##
## The decimal point is at the |
##
## 1 | 5689
## 2 | 123
## 2 | 56889
## 3 | 22224444
## 3 | 55667888
## 4 | 1
## 4 |
## 5 | 334
mtcars$wt
## [1] 2.620 2.875 2.320 3.215 3.440 3.460 3.570 3.190 3.150 3.440 3.440 4.070
## [13] 3.730 3.780 5.250 5.424 5.345 2.200 1.615 1.835 2.465 3.520 3.435 3.840
## [25] 3.845 1.935 2.140 1.513 3.170 2.770 3.570 2.780
Figuur 22. Een tabel met een wilde verzameling gewichten van 32 auto’s, gesorteerd!
Als je deze lijst vergelijkt met de stem & leafplot dan zie je de overeenkomst. Er is afgerond en samengevoegd!
The decimal point is at the |
Voorbeeld 2:
stem(mtcars$wt,scale=2) # het decimale punt is naar rechts verplaatst.
##
## The decimal point is 1 digit(s) to the left of the |
##
## 14 | 1
## 16 | 2
## 18 | 44
## 20 | 4
## 22 | 02
## 24 | 7
## 26 | 278
## 28 | 8
## 30 | 579
## 32 | 2
## 34 | 44446277
## 36 | 38
## 38 | 45
## 40 | 7
## 42 |
## 44 |
## 46 |
## 48 |
## 50 |
## 52 | 55
## 54 | 2
Voorbeeld 3:
fivenum(USArrests$UrbanPop)# % stedelijke bevolking in 50 staten van de VS.
## [1] 32 54 66 78 91
stem(USArrests$UrbanPop)
##
## The decimal point is 1 digit(s) to the right of the |
##
## 3 | 29
## 4 | 445588
## 5 | 012346789
## 6 | 002356666778
## 7 | 002234578
## 8 | 00001335679
## 9 | 1
Klopt de uitspraak: Er zijn 12 van de 50 staten met 60 - 70% stedelijke bevolking?
Een histogram geeft met steeds dezelfde intervallen aan hoe vaak een variabele voorkomt. De spreiding van een variabele wordt in beeld gebracht. De intervallen bestaan uit zogenaamde “bins”, die geven een beeld van de totale spreiding van de gegevens. De hoogte van elke bin is het aantal waarnemingen binnen ieder interval.
Een histogram is een kolomdiagram, met de staafjes tegen elkaar aan, om te laten zien dat de originele spreiding continue is.Een histogram is een visualisatie van een frequentietabel(turftabel).
par(mfrow=c(2,2),las=1,cex.axis=.5)
hist(mtcars$mpg,breaks=3,main="a. Histogram Miles per Gallon\nbreaks=3",cex.main=0.8, font.main=1, col.main="#4B3B30",xlab="Miles per gallon", ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30")
hist(mtcars$mpg,breaks=5,main="b. Histogram Miles per Gallon\nbreaks=5",cex.main=0.8, font.main=1, col.main="#4B3B30",xlab="Miles per gallon",ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30")
hist(mtcars$mpg,breaks=10,main="c. Histogram Miles per Gallon\nbreaks=10",cex.main=0.8, font.main=1, col.main="#4B3B30",xlab="Miles per gallon", ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30")
hist(mtcars$mpg,breaks=20,main="d. Histogram Miles per Gallon\nbreaks=20",cex.main=0.8, font.main=1, col.main="#4B3B30", xlab="Miles per gallon", ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30")
Afbeelding 23. a, b, c en d. Histogrammen zoals door R worden opgeleverd met steeds verschillend aantal kolommen(bins).
Het geven van verschillende kleuren aan de kolommen van een histogram is eigenlijk overbodig (of zelfs foutief), het gaat immers steeds om de zelfde variabele.
aland<-c("#312f2f","#989463","#b2aa6c","#e2bd89","#ebd1af")
barchaan<-c("#c70131", "#d31b67","#cd429b", "#b765c7", "#9384e7")
# eerste en laatste kleur vormen een sterk contrast!!! 9.04
par(mfrow=c(1,3),cex.axis=.5)
hist(mtcars$mpg,breaks=5,main="a. Histogram Miles per Gallon\nbreaks=5",
cex.main=0.8, font.main=1, col.main="#4B3B30", xlab="Miles per gallon",
ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30", col=aland)
hist(mtcars$mpg,breaks=5,main="b. Histogram Miles per Gallon\nbreaks=5",
cex.main=0.8, font.main=1, col.main="#4B3B30", xlab="Miles per gallon",
ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30", col=barchaan)
hist(mtcars$mpg,breaks=5,main="c. Histogram Miles per Gallon\nbreaks=5",cex.main=0.8, font.main=1, col.main="#4B3B30",xlab="Miles per gallon", ylab="Frequentie", cex.lab=.5, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",col="#9384e7")
Figuur 24. a, b en c. Kleurijke Windowdressing, de derde afbeelding (c) is de standaard - en correcte weergave van een histogram.
Een dichtheidsplot is een vloeiende versie van het histogram. Het visualiseert de verdeling van gegevens met een continu interval. Een dichtheidsplot wordt niet beïnvloed door het aantal gebruikte “bins”.
par(las=1)
hist(mtcars$mpg, # histogram
col="#ebd1af", # kolomkleur
border="black",
prob = TRUE, # show densities inplaats van frequencies
xlab = "Miles per Gallon",
main = "Histogram en densityplot gecombineerd weergegeven.")
lines(density(mtcars$mpg), # density plot
lwd = 2, # lijndikte
col = "#c70131")
Figuur 25. Histogram met densityplot.
Ter aanvulling een histogram met 25 bins gecombineerd met een densityplot, de densityplot (lijn) blijft onveranderd weergegeven.
par(las=1)
hist(mtcars$mpg, # histogram
breaks=25,
col="#ebd1af", # kolomkleur
border="black",
prob = TRUE, # show densities inplaats van frequencies
xlab = "Miles per Gallon",
main = "Histogram en densityplot gecombineerd weergegeven.")
lines(density(mtcars$mpg), # density plot
lwd = 2, # lijndikte
col = "#c70131")
Figuur 26. Histogram met densityplot.
Bij horizontale- en vertikale staafdiagrammen vormen de lengte van de staaf, het eindpunt en het gebied (omtrek en vulling) samen de “visuele codering” van de data. De eerste codering die wordt geregistreerd is het eindpunt van de staaf, positie en lengte zijn zogenaamde “secondaire coderingen”.
Bij een kolomdiagram hebben de x- en y-as veelal een kwantitatieve schaal. Horizontale staafdiagrammen hebben veelal op de y-as een kwalitatieve schaal (categorieën of rangorde). Veelal, omdat daar van kan worden afgeweken (flexibel). Wel is bij een vertikale staafdiagram meer ruimte voor horizontale labels. Horizontaal plaatsen van labels heeft altijd de voorkeur boven verticale plaatsing of in een bepaalde hoek van plaatsing.
par(mfrow=c(3,2),las=1)
H<-c(5,10,15,20)
barplot(H,main="a. Kolomdiagram",col="#ff674d")
H<-c(15,10,5,20)
barplot(H,main="b. Kolomdiagram",col="#e37c2e")
H<-c(20,15,10,5)
barplot(H,main="c. Kolomdiagram",col="#e37c2e")
V<-c(15,10,5,20)
barplot(H,main="d. Staafdiagram",hor=TRUE,col="#9f9928")
V<-c(5,10,15,20)
barplot(V, main="e. Staafdiagram",hor=TRUE,col="#7ca041")
V<-c(20,15,10,5)
barplot(V,main="f. Staafdiagram",hor=TRUE,col="#58a35e")
Figuur 27 a, b, c, d, e en f. De standaarddiagrammen.
par(las=1,mar=c(5,15,5,5),cex=0.6,fg="#336089")
auto.names = row.names(mtcars)
barplot(mtcars$mpg,names.arg = auto.names,main="Miles per Gallon",col.main="#336089",
xlab="Miles", ylab="",col="#336089",col.lab="#336089",col.axis="#336089",
horiz = TRUE)
Figuur 28. Bij voorkeur lange labels in staafdiagram plaatsen in verband met de leesbaarheid.
par(mfrow=c(2,1), bg="#CFBFB4",fg="yellow")
vector01 <- c('a','a', 'b','b','a','a','b')
table(vector01)
## vector01
## a b
## 4 3
# ann =TRUE of ann =FALSE , wel of geen aslabels
barplot(table(vector01),las=1, ylim=c(0,4), main="a. Barplot met y-axis tot 4",ann=TRUE,border="yellow",col="yellow",
names.arg = c("A", "B"), cex.names = 1,space=c(0.1))
barplot(table(vector01),las=1, ylim=c(0,4), main="b. Barplot met y-axis tot 4",ann=TRUE,border=NA,col="yellow",horiz = TRUE,
names.arg= c("A", "B"), cex.names = 1,space=c(0.1))
Figuur 29 a en b. Met wat kleur en beperking van de y-as tot waarde 4.
cyl.freq<-table(mtcars$cyl)
cyl.freq
##
## 4 6 8
## 11 7 14
barplot(cyl.freq,las=1,main="Aantal auto's met\n4, 6 of 8 cylinders",adj=0,col="#4B3B30")
Figuur 30. Gegroepeerd op aantal cylinders.
De tabellen van mtcars$am = transmission (0 = automatic, 1 = manual)
table(mtcars$cyl[mtcars$am==0])
##
## 4 6 8
## 3 4 12
table(mtcars$cyl[mtcars$am==1])
##
## 4 6 8
## 8 3 2
cyl.freq.matrix <-table(mtcars$am,mtcars$cyl)
barplot(cyl.freq.matrix,beside=TRUE,horiz=TRUE,las=1,adj=0,
main="Performance car counts\nby transmission and cylinders",names.arg=c("V4","V6","V8"),legend.text=c("Automatic","Manual"),args.legend=list(x="bottomright",bty="n"))
grid(nx=NULL,ny=NULL,lty = 3,col=("gray"),lwd = 0.1)
Figuur 31. Auto’s met aantal cylinders en soort transmissie.
cyl.freq.matrix <-table(mtcars$am,mtcars$cyl)
barplot(cyl.freq.matrix,beside=TRUE,horiz=FALSE,las=1,adj=0,
main="Performance car counts\nby transmission and cylinders",
names.arg=c("V4","V6","V8"),legend.text=c("Automatic","Manual"),
args.legend=list(x="topleft",bty="n"))
grid(nx=NULL,ny=NULL,lty = 3,col=("gray"),lwd = 0.1)
Figuur 32.Auto’s met aantal cylinders en soort transmissie.
counts <- table(mtcars$vs, mtcars$gear)
par(bg ="#4B3B30",fg="white ",las=1,lty=0,adj=0)
barplot(col.axis="white",counts,main="Aantal auto's, aantal versnellingen en V-motor",ylab="Auto's",
col.main="white",xlab="Aantal Versnellingen",font=2,
col=c("#1565C0","darkorange"),col.lab="white")
legend (2.4,14, legend=c("Met V-motor","Zonder\nV-motor"),fill = c ("darkorange","#1565C0"))
mtext("©2021 Hans den Hartog",line = 6, cex=.8,side=1,adj=1)
Figuur 33. Gestapelde kolomdiagram.
counts <- table(mtcars$vs, mtcars$gear)
par(bg ="#4B3B30",fg="white ", las=1, lty=0,adj=0)
barplot(col.axis="white",counts,main="Aantal auto's, aantal versnellingen en V-motor",ylab="Versnellingen",
col.main="white", xlab="Aantal Auto's",font=2,
col=c("#1565c0","darkorange"),col.lab="white",horiz=TRUE)
legend (8,3.5, legend=c("Met V-motor","Zonder\nV-motor"),fill=c("darkorange","#1565C0"))
mtext("©2021 Hans den Hartog",line = 6, col ="mintcream", cex=.8,side=1,adj=1)
Figuur 34. Gestapelde staafdiagram.
Ook bij staaf- en kolomdiagrammen moet het kleurgebruik functioneel zijn. Als het om één variabele gaat draagt het gebruik van meerdere kleuren weinig bij aan de kwaliteit van de visualisatie van informatie.
Drie voorbeelden, het gebruiken van gradiëntkleuren suggereert een op- of aflopende waarde. Als daar geen sprake van is, gebruik dan 1 kleur voor de staafjes en kolommen of in het geval van meerdere categorieën een categoriaal kleurpalet.
wolkenlucht<-c("#ffffff","#DAEDF3","#C8D6E9","#9BB6D0","#4C77A2","#3B6893","#2C5780")
palet001<-c("#40464b","#acd2a3","#f9f4ea","#f0c1b9","#cce5d7","#9ac4c3","#f0d94a")
par(mfrow=c(2,2),bg=("#eff9ff"),las=1)
barplot(1:7,main="a.Kleurpalet\n(gradiënt)",
xlab="",ylab="7 Kleuren",col.lab =("white"),
border=NA,col=wolkenlucht,horiz =TRUE,xaxt="n", ann=TRUE,yaxt="n") # geen as en geen label
barplot(1:7,main="b.Kleurpalet\n(gradiënt)",
xlab="",ylab="7 Kleuren",col.lab =("white"),
border=NA,col=wolkenlucht,horiz =FALSE,xaxt="n", ann=TRUE,yaxt="n")# geen as en geen label
barplot(1:7,main="c.Kleurpalet (categoriaal).",
xlab="",ylab="1 Kleur",col.lab =("white"),
border=NA,col=palet001,horiz =FALSE,xaxt="n", ann=TRUE,yaxt="n")# geen as en geen label
barplot(1:7,main="d.Kleurpalet beperkt tot één kleur.",
xlab="",ylab="1 Kleur",col.lab =("white"),
border=NA,col=("#2C5780"),horiz =FALSE,xaxt="n", ann=TRUE,yaxt="n")# geen as en geen label
figuur 35. a, b, c en d. Toepassen van kleur bij staaf- en kolomdiagrammen.
barchaan10<-c("#a52a4e","#b61640","#c70131","#3c83b5","#49b6e5","#12c5f6","#4dd4f8","#88e2f9","#c3f0fb","#fefefc")
winst<-c(514,410,400,390,380,370,310,300,250,240)
par(mar=c(5,10,5,5),bg="#FFADAD")
barplot(winst,names.arg=c("Walmart","Sinopec","Shell","China Petroleum","State Grid","Saudi Aramco","BP","Exxon","VW","Toyota"),
main="10 Grootste Bedrijven in 2019",adj=1,
xlab="Winst in miljoenen $",
ylab="",
border=NA,las=1,
col=barchaan10,horiz =TRUE,xaxt="n", ann=TRUE)
figuur 36. Correct toepassen van kleur bij staaf- en kolomdiagrammen.
par(mfrow=c(1,3),mar = c(5.1, 5.1, 4.1, 2.1),las=1)
# Set the margin bottom, top, left , right
state.names = row.names(USArrests)
barplot(USArrests$Assault,names.arg = state.names,col="deeppink",
ylim=c(0,350),cex.axis =1,main = "a.Assault Rate in the\nUSA in 1973",
ylab = "Number of arrests",
cex.names = .6, horiz = FALSE, xlab = "50 Staten",border=NA)
barplot(USArrests$Rape,names.arg = state.names,col="darkorange",
xlim=c(0,50),cex.axis =1,main = "b. Rape Rate in the\nUSA in 1973",
ylab = "",
cex.names = .6, horiz = TRUE, xlab = "Number of Arrests",border=NA)
barplot(USArrests$Murder,names.arg = state.names,col="deeppink",
ylim=c(0,20),cex.axis =1,main = "c. Murder Rate in the\nUSA in 1973",
ylab = "Number of arrests",
cex.names = .6, horiz = FALSE, xlab = "50 Staten",border=NA)
Figuur 37 a, b en c met de 50 namen van staten van de Vs en typen misdrijven.
par(las=1,cex=0.75)
plot(mtcars$mpg,type="n",main="Voorbeelden van het gebruik van legend()")
legend( "topleft",legend=paste("color",1:3),fill=grey(c(0.2,0.5,0.8)),border=0,
bg="grey95",box.lwd=3,box.lty="dashed",box.col="grey20",text.col="grey20",text.font=3,horiz=TRUE,
title="Voorbeeld van vullen",title.col="grey5",title.adj=0,inset=c(0.01,0.014))
legend("topright", legend=paste("pch",21:23), pch=21:23,pt.bg="grey80", cex=1.2,pt.cex=1.2,pt.lwd=2,
bg="grey99",box.lwd=2,box.col="grey40",text.col="grey20",text.font=3,title="Voorbeeld van pch",
title.col="grey5",title.adj=0.5, inset=c(0.01,0.014))
legend(0.5,40,legend=paste("lty",1:3),col=grey(c(0.2,0.5,0.7)),lty=1:3,,lwd=1:3,bg="grey97",box.lwd=2,box.col="grey60",cex=0.95,text.col=grey(c(0.2,0.5,0.7)), text.font=1,ncol=2,title="Voorbeeld van lty,lwd & col", title.col="grey5",title.adj=1,seg.len=2.5)
# seg.len = lengte van element
legend(c(3,25),c(20,25),legend=paste("voorbeeld",1:3),fill=grey(c(0.7,0.5,0.2)),col=grey(c(0.2,0.5,0.7)),
lty=1:3,lwd=2,pch=21:23,bg="grey96",box.lwd=2,box.col="grey60",pt.bg=grey(c(0.7,0.5,0.2)),pt.cex=1.2,#pt=points
text.col=grey(c(0.2,0.5,0.7)),text.font=1,merge=FALSE,title="Voorbeeld van boxes,pch's & lLines",
title.col="grey5",seg.len=2.5)
legend("bottomright",legend=paste("default",1:3),fill=paste0("grey",c(75,60,45)),bty="n")
Figuur 38. Legendatypen en positie.
#install.packages("beeswarm")
library("beeswarm")
# options(scipen=999) zet wetenschappelijke notatie van getallen uit
beeswarm(mtcars$mpg,main="Aantal Miles per Gallon",sub="Elke stip is een auto (32 auto's totaal),las=1")
Afbeelding.39
par(mfrow=c(2,2),mar=c(5,5,5,5)+0.1)
hist(mtcars$mpg, breaks=5,main="Histogram Miles \nper Gallon")
stripchart(mtcars$mpg,main="Stripchart Miles \nper Gallon")
# 2x Beeswarm
data(mtcars)
beeswarm(mtcars$mpg ~ mtcars$cyl, data = mtcars,
pch = 16, main = "Beeswarm Mtcars \nMiles per Gallon",
xlab = "Aantal cylinders", ylab = "Aantal miles")
beeswarm(mtcars$mpg ~ mtcars$cyl, data = mtcars,
log = TRUE, pch = 16, col = rainbow(3),xlab="Aantal cylinders", ylab="Aantal miles",
main = 'Beeswarm Mtcars \nMiles per Gallon',las=1)
Afbeelding.40
# Beeswarm opties
library("RColorBrewer")
par(mar=c(5,5,3,1),las=1,pch=19, cex=1.5, bg="#CFBFB4",bty="n",fg="ghostwhite",adj=1)
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=brewer.pal(n = 3, name = "RdBu"),
pch=19, method="swarm", cex=1,
xlab="Aantal cylinders",ylab= "Miles per Gallon",
col.lab="ghostwhite",col.axis="ghostwhite",
main="Brandstofverbruik Auto met Aantal Cylinders",
col.main="ghostwhite")
Afbeelding 41. Methode swarm.
par(las=1,pch=19, cex=1.5, bg="#CFBFB4",bty="n",fg="ghostwhite")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=brewer.pal(n = 3, name = "RdBu"), pch=19, method="center", cex=1)
Afbeelding 42. Methode center.
par(las=1,pch=19, cex=1.5, bg="#CFBFB4",bty="n",fg="ghostwhite")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=brewer.pal(n = 3, name = "RdBu"), pch=19, method="hex", cex=1)
Afbeelding 43. Methode hex.
par(las=1,pch=19, cex=1.5, bg="#CFBFB4",bty="n",fg="ghostwhite")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=brewer.pal(n = 3, name = "RdBu"), pch=19, method="square", cex=1)
Afbeelding 44. Methode square.
library("RColorBrewer")
par(mfrow=c(2,2),las=1, bg="#F1F2ED")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=sample(colors(), 27), pch=19,
method="swarm", cex=0.9, horizontal=TRUE, xlab="Miles per Gallon",
ylab="Aantal cylinders",
main="Hoe meer cylinders,\nhoe minder miles per gallon\nkeus uit 27 kleuren", bty="n")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=sample(colors(), 27), pch=19,
method="center", cex=0.9, horizontal=TRUE, xlab="Miles per Gallon",
ylab="Aantal cylinders",
main="Hoe meer cylinders,\nhoe minder miles per gallon\nkeus uit 27 kleuren", bty="n")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=sample(colors(), 3), pch=19,
method="swarm", cex=0.9, horizontal=TRUE, xlab="Miles per Gallon",
ylab="Aantal cylinders",
main="Hoe meer cylinders,\nhoe minder miles per gallon\nkeus uit 3 kleuren", bty="n")
beeswarm(mtcars$mpg ~ mtcars$cyl, data=mtcars, col=sample(colors(), 3), pch=19,
method="center", cex=0.9, horizontal=TRUE, xlab="Miles per Gallon",
ylab="Aantal cylinders",
main="Hoe meer cylinders\nhoe minder miles per gallon\nkeus uit 3 kleuren", bty="n")
Afbeelding 45. Methode swarm & center.
par(mfrow=c(1,2),las=1,bg="#9E1A1F",fg="white",bty="n",
col.axis="white",col.lab="white")
boxplot(mtcars$mpg ~ mtcars$cyl, data = mtcars ,
outline = FALSE, # avoid double-plotting outliers, if any
main = 'Boxplot + Beeswarm\noutline=False',col.main="white")
beeswarm(mtcars$mpg ~ mtcars$cyl, data = mtcars,
col = 4, pch = 16,cex=1.5, add = TRUE)
boxplot(mtcars$mpg ~ mtcars$cyl, data = mtcars,
outline=TRUE,
main = 'Boxplot + Beeswarm\noutline=TRUE',col.main="white")
beeswarm(mtcars$mpg ~ mtcars$cyl, data = mtcars,
col = "orange", pch = 16,cex=1.5,add=TRUE)
Afbeelding 46. Outline on / off.
par(mfrow=c(2,3),las=1,pch=19, cex=0.9,bg="#FFFFFF",bty="n")
stripchart(mtcars$mpg,main = "a. Miles per Gallon",col.main="#666666",method="jitter",
col="#212121",pch=1, vertical = TRUE, ylab = "Aantal auto's")
stripchart(mtcars$gear,main = "b. Aantal\nVersnellingen",col.main="#666666", method="jitter",
col="#1565C0",pch=1, vertical = TRUE, ylab = "Aantal Versnellingen")
stripchart(mtcars$hp,main = "c. Aantal\npaardenkrachten",col.main="#666666", method="stack",
col="#ff8c00",pch=1, vertical = TRUE, ylab = "Aantal paarden krachten")
stripchart(mtcars$wt,main = "d. Gewicht van\n32 auto's",col.main="#666666",method="jitter",
col="#212121",pch=1, vertical = TRUE, ylab = "Gewicht lbs.")
stripchart(mtcars$cyl,main = "e. Aantal cylinders",col.main="#666666", method="stack",
col="#1565C0",jitter=0.5,pch=1, vertical = TRUE, ylab = "Aantal cylinders")
stripchart(mtcars$am,main = "f. Automaat of\nmet Versnellingen",col.main="#666666", method="jitter",
col="#ff8c00",pch=1, vertical = TRUE, ylab = "wel of geen automaat")
Figuur 47. a, b, c, d, e en f. Standaard Stripcharts.
par(mfrow=c(1,2),las=1,pch=19, cex=0.8, bty="n",bg="#FFFFFF")
x <- list("mpg" = mtcars$mpg, "wt"=mtcars$wt,"cyl" = mtcars$cyl,
"vs" = mtcars$vs, "gear" = mtcars$gear)
# Maak plot met een strip per variabele
stripchart(x, main = "a. Autodataset (mtcars met 32 auto's)",col.lab="#444347",
xlab = "",
ylab = "Eigenschappen auto",
col = c("steelblue", "coral2"),
pch = 16,
method = "jitter")
stripchart(x,
main = "b. Auto-eigenschappen (mtcars)",col.lab="#444347",
xlab = "",
ylab = "Aantal",
col = c("steelblue", "coral2"),
pch = 16,
method = "stack",vertical=TRUE)
Figuur 48. a en b. Meerdere Stripcharts in één grafiek.
# calculate a correlation matrix for numeric variables
# install.packages("corrplot")
library(corrplot)
## corrplot 0.90 loaded
correlations <- cor(mtcars[,1:11]) # 11 variabelen.
# display the correlation matrix/hoe dichter bij 1 hoe sterker de samenhang (pos. of negatief)
print(correlations)
## mpg cyl disp hp drat wt
## mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594
## cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958
## disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799
## hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479
## drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406
## wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000
## qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159
## vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157
## am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953
## gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870
## carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059
## qsec vs am gear carb
## mpg 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
## cyl -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
## disp -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
## hp -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
## drat 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
## wt -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
## qsec 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
## vs 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
## am -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
## gear -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
## carb -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
par(mfrow=c(1,3))
corrplot(correlations, method = "circle")
corrplot(correlations, method = "square")
corrplot(correlations, method = "ellipse")
Figuur 50. a, b en c. Corrplot met correlaties,method= circle, square of ellipse.
par(mfrow=c(1,3))
corrplot(correlations, method = "shade")
corrplot(correlations, method = "color")
corrplot(correlations, method = "pie")
Figuur 51. d, e en f. Corrplot met correlaties, method= number, shade, color of pie.
library(corrgram)
corrgram(USArrests, order=NULL, lower.panel=panel.shade,
upper.panel=NULL, text.panel=panel.txt,
main="The depth of the shading indicates the magnitude of the correlation")
Figuur 52. Corelogram.
x <- c(10,20,30,40,50)
y1 <-c(4,6,5,3,7)
par(las=1)
plot(x,y1, type="l",col="red" ,ylab="y1 & y2 4 t/m 14", yaxt="n")
Figuur 53. Spreidingsdiagram.
x <- c(10,20,30,40,50)
y1 <-c(4,6,5,3,7)
y2<-c(10,11,12,13,14)
par(las=1)
plot(x, y1, type="l", col="red" ,ylab="y1 & y2 4 t/m 14", yaxt="n")
par(new=TRUE,las=1)
plot(x, y2, type="l", col="green",ylab="",yaxt="n")
legend ("topleft", legend=c("y1","y2"),fill=c("red","green"),bty="n")
Figuur 534. Spreidingsdiagram met twee plots in 1 diagram, met plot().
cylfactor<- factor(mtcars$cyl)
plot(cylfactor,las=1,main = "Barplot")
Figuur 55. Staafdiagram met plot().
plot(cylfactor,mtcars$hp, las=1,main = "Boxplot",xlab="Aantal Versnellingen",ylab="Paardenkracht")
Figuur 56. Boxplot met plot().
neerslag <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)
plot(neerslag,type="l",las=1)
Figuur 57. Lijngrafiek met plot().
opgaandeLijn <- function(x) x^3
# Plot R function
plot(opgaandeLijn, 0, 10,las=1, main = "Plot a function")
Figuur 58. Functieweergeven met plot().
plot(mtcars[, 1:4],las=1,main="Correlatie plot \n4 variabelen")
Figuur 59. Correlaties met plot().
plot(mtcars[, 1:11],las=1, main = "Correlatie plot\n 11 variabelen")
Figuur 60. Correlaties met plot().
Boxplot(box-and-whisker plot): minimum,1e quartiel, mediaan, 2e quartiel, maximum top van 2e quartiel is 75% v.d. waarnemingen
vector01 <- c(10,24,56,34,18,12,78)
vector02 <-c( 12,38,45,14,12,124)
boxplot (vector01,vector02,horizontal=TRUE,names=c("Verzameling 1", "Verzameling 2"))
Figuur 61. Boxplot standaard, horizontaal.
data<-mtcars
x<-data$hp
boxplot(x=x, data=data, las=1)
Figuur 62. Boxplot standaard, horizontaal.
Of wat completer
boxplot(mpg~cyl,data=mtcars, main="Car Milage Data",
xlab="Number of Cylinders", ylab="Miles Per Gallon",varwidth = T,las=1)
Figuur 63. Boxplot standaard verticaal. Met één uitbijter.
par(las=1,bg="#E9EDF0")
boxplot(mpg~cyl,data=mtcars, main="Car Milage Data",frame=FALSE,
xlab="", ylab="Miles Per Gallon",varwidth = T,
names=c("4\ncylinder","6\ncyclinder","8\ncylinder"))
Figuur 64. Boxplot standaard verticaal. Met extra labels op de x-as.
# alternatief
# mtext("4 cylinder 6 cylinder 8 cylinder", side=1, line=3, cex.lab=1,las=1, col="blue")
par(mfrow=c(2,2),las=1,bg="#EDE7E3")# twee rijen in twee kolommen
boxplot(mtcars[,0:4],main="Mtcars: Vier Variabelen")
boxplot(mtcars[,0:4],main="Mtcars: Vier Variabelen",horizontal = TRUE)
boxplot(mtcars[,0:11],main="Mtcars: Elf Variabelen")
boxplot(mtcars[,0:11],main="Mtcars: Elf Variabelen",horizontal = TRUE)
Figuur 65. Boxplot.
x = c(10,11,12,13,14,15,16,19,20,24,26,30,45)
boxplot(x, main= "Boxplot:Gemiddelde of Mediaan\n(Standaard!)", ylab="aantal", las=1, col="#4B3B3020")
abline(h=19.61538, col="#1565C0",lty=3)# gemiddelde
abline(h=16, col="#ff8c00",lty=3)# mediaan
text("Gemiddelde", x=1,y=21,col=c("#1565c0"))
text("Mediaan",x=1,y=17,col=c("#ff8c00"))
Figuur 66. Boxplot.
# dev.new(width=5, height=4)#afmeting plotscherm
par(mfrow=c(2,2), mar=c(1,5,5,2), bg= "#CFBFB4", fg="#F1F2ED",las=1)
boxplot(mtcars$mpg,main="a. Boxplot Miles per Gallon",cex.main=1.3, font.main=2, col.main="#4B3B30",
xlab="Automerken in Mtcars",ylab="Miles per Gallon", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",
sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58",horizontal=FALSE)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "#DFD4CD80")
boxplot(mtcars$mpg,main="b. Boxplot Miles per Gallon",cex.main=1.3, font.main=2, col.main="#4B3B30",
xlab="Miles per gallon",ylab="Automerken in Mtcar", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",
sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58",horizontal=TRUE)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "#DFD4CD80")
boxplot(mtcars$mpg,main="c. Boxplot Miles per Gallon",cex.main=1.3, font.main=2, col.main="#4B3B30",
xlab="Miles per gallon",ylab="Automerken in Mtcar", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",
sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58",horizontal=TRUE,frame=FALSE)
stripchart(mtcars$mpg,method="jitter",add=TRUE,frame=FALSE)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "#DFD4CD80")
boxplot(mtcars$mpg,main="d. Boxplot Miles per Gallon",cex.main=1.3, font.main=2, col.main="#4B3B30",
xlab="Automerken in Mtcars",ylab="Miles per Gallon", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",
sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58",horizontal=FALSE,frame=FALSE)
stripchart(mtcars$mpg,method="jitter",add=TRUE,frame=FALSE,vertical = TRUE)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "#DFD4CD80")
Figuur 67. a, b, c en d. Boxplots.
# dev.new(width=5, height=4) # Afmeting plotscherm
par(mar=c(10,5,5,2), bg= "#CFBFB4", fg="#F1F2ED",las=1,adj=0)
boxplot (mtcars$mpg~mtcars$hp,main="Boxplot Miles per Gallon en Paardenkracht",cex.main=1.3, font.main=2, col.main="#4B3B30",
xlab="Paardenkracht",ylab="Miles per Gallon", cex.lab=1.1, font.lab=1, col.lab="#4B3B30",col.axis="#4B3B30",
sub=(auteur), cex.sub=0.8, font.sub=3, col.sub="#896B58",horizontal=FALSE,frame=FALSE)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "#DFD4CD80")
Figuur 68. Boxplot.
x<-c(70,60,51,40,20)
labels<-c("Maruti","Tata","VW","Toyota","Honda")
pie(x,labels,clockwise=TRUE)#aangepast sorteren segmenten van groot naar klein in de kijkrichting wijzers klok!
Figuur 69. Taartdiagram of pie.
attach(USArrests)
## The following objects are masked from USArrests (pos = 7):
##
## Assault, Murder, Rape, UrbanPop
#variabele "death" wordt berekend uit de waarden van drie andere variabelen
arrests=c(sum(Assault),sum(Rape),sum(Murder))
# Met de variabele "cols" krijgen de drie berekende variabelen een verschillende kleur"
cols<-c("pink","lightblue","darkgreen")
# bereken de procentuele verdeling van de drie variabelen in het geheel van 100% en sla dat op in de variabele "percentlabels"
percentlabels<- round(100*arrests/sum(arrests), 1)#1=afronden op 1 decimaal
pielabels<- paste(percentlabels, "%", sep=" ")
pie(arrests,clockwise = TRUE, labels=pielabels,col=cols,main="Arrests per category",sub="All states")
legend("topright", c("Assault","Rape","Murder"), cex=0.8, fill=cols, bty = "n",border=NA)
Figuur 70. Taartdiagram of pie, segementen gesorteerd op grootte met de wijzers van de klok mee..
attach(USArrests)
## The following objects are masked from USArrests (pos = 3):
##
## Assault, Murder, Rape, UrbanPop
## The following objects are masked from USArrests (pos = 8):
##
## Assault, Murder, Rape, UrbanPop
# Variabele "death" wordt berekend uit de waarden van drie andere variabelen
arrests=c(sum(Murder),sum(Rape),sum(Assault))
# Met de variabele "cols" krijgen de drie berekende variabelen een verschillende kleur"
cols<-c("pink","lightblue","darkgreen")
# Bereken de procentuele verdeling van de drie variabelen in het geheel van 100% en sla dat op in de variabele "percentlabels"
percentlabels<- round(100*arrests/sum(arrests), 1)#1=afronden op 1 decimaal
pielabels<- paste(percentlabels, "%", sep=" ")
pie(arrests,clockwise = TRUE, labels=pielabels,col=cols,main="Arrests per category",sub="All states")
legend("topright", c("Murder","Rape","Assault"), cex=0.8, fill=cols, bty = "n")
Figuur 71. Taartdiagram of pie. Gelijk aan de afbeelding van figuur 70, maar nu zijn de kleuren veranderd. Heeft dit invloed op de kijker/lezer?
x <-c(60,20,10,10)
pie( x, labels = c("Lucht", "Zonnige kant van de pyramide",
"Schaduwkant van de piramide"),
xlab =" ", ylab =" ",
col = c(" cornflowerblue","gold","gray"),
border=NA, main =" De enige reden om een zinvolle taartdiagram te maken:")
Figuur 72. Een piramide met een wolkloze hemel. Taartdiagram of pie is onderwerp van felle discussies. Wel of niet toepassen of vervangen door een tabel of staaf-of kolomgrafiek?
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:car':
##
## recode
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
USArrests = select(USArrests,-3)
library(pheatmap)
attach(USArrests)
## The following objects are masked from USArrests (pos = 5):
##
## Assault, Murder, Rape
## The following objects are masked from USArrests (pos = 6):
##
## Assault, Murder, Rape
## The following objects are masked from USArrests (pos = 11):
##
## Assault, Murder, Rape
data.matrix(USArrests)
## Murder Assault Rape
## Alabama 13.2 236 21.2
## Alaska 10.0 263 44.5
## Arizona 8.1 294 31.0
## Arkansas 8.8 190 19.5
## California 9.0 276 40.6
## Colorado 7.9 204 38.7
## Connecticut 3.3 110 11.1
## Delaware 5.9 238 15.8
## Florida 15.4 335 31.9
## Georgia 17.4 211 25.8
## Hawaii 5.3 46 20.2
## Idaho 2.6 120 14.2
## Illinois 10.4 249 24.0
## Indiana 7.2 113 21.0
## Iowa 2.2 56 11.3
## Kansas 6.0 115 18.0
## Kentucky 9.7 109 16.3
## Louisiana 15.4 249 22.2
## Maine 2.1 83 7.8
## Maryland 11.3 300 27.8
## Massachusetts 4.4 149 16.3
## Michigan 12.1 255 35.1
## Minnesota 2.7 72 14.9
## Mississippi 16.1 259 17.1
## Missouri 9.0 178 28.2
## Montana 6.0 109 16.4
## Nebraska 4.3 102 16.5
## Nevada 12.2 252 46.0
## New Hampshire 2.1 57 9.5
## New Jersey 7.4 159 18.8
## New Mexico 11.4 285 32.1
## New York 11.1 254 26.1
## North Carolina 13.0 337 16.1
## North Dakota 0.8 45 7.3
## Ohio 7.3 120 21.4
## Oklahoma 6.6 151 20.0
## Oregon 4.9 159 29.3
## Pennsylvania 6.3 106 14.9
## Rhode Island 3.4 174 8.3
## South Carolina 14.4 279 22.5
## South Dakota 3.8 86 12.8
## Tennessee 13.2 188 26.9
## Texas 12.7 201 25.5
## Utah 3.2 120 22.9
## Vermont 2.2 48 11.2
## Virginia 8.5 156 20.7
## Washington 4.0 145 26.2
## West Virginia 5.7 81 9.3
## Wisconsin 2.6 53 10.8
## Wyoming 6.8 161 15.6
pheatmap(USArrests,cluster_row= FALSE,cluster_col= FALSE,main="Arrests per category and per state")
Figuur 73. Heatmap.
mtcars_order <- mtcars[order(mtcars$hp),]
mtcars_matrix <- data.matrix(mtcars_order)
heatmap(mtcars_matrix, Colv = NA, Rowv = NA, scale = "column",
main = "Autokenmerken", sub = "Gerangschikt op individueel kenmerk",
cexCol = 1, cexRow = 1)
Figuur 74. Heatmap.
x <- mtcars[order(mtcars$mpg),] # gesorteerd op mpg
x$cyl <- factor(x$cyl) # het moet een factor zijn
x$color[x$cyl==4] <- "red"
x$color[x$cyl==6] <- "blue"
x$color[x$cyl==8] <- "darkgreen"
dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
main="Benzineverbruik voor Automerken (typen)\ngegroepeerd op aantal cylinders",
xlab="Miles Per Gallon", gcolor="black", color=x$color)
Figuur 75. Dotplot of Dotchart.
attach(USArrests)
## The following objects are masked from USArrests (pos = 3):
##
## Assault, Murder, Rape
## The following objects are masked from USArrests (pos = 6):
##
## Assault, Murder, Rape
## The following objects are masked from USArrests (pos = 7):
##
## Assault, Murder, Rape
## The following objects are masked from USArrests (pos = 12):
##
## Assault, Murder, Rape
par(mfrow=c(1,3),las=1,pch=19, cex=0.8)
dataGesorteerd=USArrests[order(USArrests$Assault),]
state.names = row.names(USArrests)
dotchart(dataGesorteerd$Assault,xlab= "Number of arrests",labels=row.names(dataGesorteerd),cex=.6,col=c("black","blue"),cex.lab=1.5,las = 2, main = "Assault Rate in the\nUnited States in 1973")
dataGesorteerd=USArrests[order(USArrests$Murder),]
state.names = row.names(USArrests)
dotchart(dataGesorteerd$Murder,xlab= "Number of arrests",labels=row.names(dataGesorteerd),cex=.6,,col=c("black","blue"),cex.lab=1.5,las = 2, main = "Murder Rate in the\nUnited States in 1973")
dataGesorteerd=USArrests[order(USArrests$Rape),]
state.names = row.names(USArrests)
dotchart(dataGesorteerd$Rape,xlab= "Number of arrests",labels=row.names(dataGesorteerd),cex=.6,,col=c("black","blue"),cex.lab=1.5,las = 2, main = "Rape Rate in the\nUnited States in 1973")
Figuur 76. Dotplot of Dotchart.
state.names = row.names(USArrests)