Rmd

Grafiken mit vorab berechneten Werten, die für die Darstellung benutzt werden sollen

Die graphisch darzustellenden Werte liegen bereits vor und werden nicht von ggplot() ermittelt.

Das Prinzip wird sehr schön erklärt auf Christian Treffenstädts rspace unter grafiken

Auch bei r-cookbook werden die Minimalangaben in einem kleinen Dataframe gespeichert und benutzt bar graphs

Wichtig: Alle Werte, die in einem geom...() verwendet werden sollen, müssen in einem Dataframe gespeichert sein. Vgl. aber auch die Ausführungen zu “Grafiken auf Basis von mehreren Datenquellen”

Der entscheidende Parameter ist stat="identity"), was bedeutet, dass als Ergebnis der Berechnung (stat) der Wert selbst zurückgegeben wird, mit anderen Worten also nichts berechnet wird bzw. das Ergebnis gleich dem Wert ist, der übergeben wurde.

Ein erstes Beispiel

require("ggplot2")
## Loading required package: ggplot2
# define dataframe 3 groups, gender and two vars (weight and height)
dd <- data.frame(
  m.weight=c( 50,  55,  75,  77,  90,  98), 
  m.height=c(165, 184, 170, 179, 167, 182), 
  group=factor(c(rep(1,2),rep(2,2),rep(3,2))), 
  gender=factor(c(rep(c(1,2),3)))
  )
ggplot(data=dd, 
  aes(x=group, y=m.weight, fill=gender)) + 
  geom_bar(stat="identity", position=position_dodge(), colour="black")

Aufbereitung für ggplot() mit Rmisc::SummarySE()

Die Funktion summarySE() erstellt aus einem Dataframe einen über Gruppenvariablen aggregierten Dataframe mit descriptiven Statistiken. Wir können einen solchen Ergebnis-Dataframe nutzen, um ggplot-Grafiken zu erstellen.

# define dataframe 3 groups, gender and two vars (weight and height)
dd <- data.frame(
  m.weight=c( 50,  55,  75,  77,  90,  98,     53,  57,  76,  75,  91,  99), 
  m.height=c(165, 184, 170, 179, 167, 182,    166, 183, 171, 179, 174, 183), 
  group=factor(c(rep('a',2),rep('b',2),rep('c',2),rep('a',2),rep('b',2),rep('c',2))), 
  gender=factor(c(rep(c('f', 'm'),6)))
  )
# we use summarySE to calculate group descriptives
require(Rmisc)
## Loading required package: Rmisc
## Loading required package: lattice
## Loading required package: plyr
ggframe <- Rmisc::summarySE(data = dd, measurevar = 1, groupvars = c(3))

# we get a data frame with all required parameters for the plot
ggframe
##   group N     1        sd        se       ci
## 1     a 4 53.75 2.9860788 1.4930394 4.751518
## 2     b 4 75.75 0.9574271 0.4787136 1.523480
## 3     c 4 94.50 4.6547467 2.3273733 7.406741
# we use that for ggplot
ggplot(ggframe, aes(x = factor(group), y = ggframe[,3])) + 
geom_bar(stat = "identity", width = 0.5, aes(fill = factor(group))) + 
labs(title = "Gewichtsgruppe", x = "Gruppenzugehörigkeit", y = "Gewicht (kg)") + 
geom_errorbar(aes(ymin = ggframe[, 3] - ci, ymax = ggframe[, 3] + ci), width = 0.1, size = 0.5)

Mehrere geom...(), Wirkungsweise von stats, Zusammenspiel mit geom...()

Wenn für ein geom...() über die Einzeldaten aggregiert werden muss, kommt stat() zum Einsatz. stat="identity" sorgt dafür, dass die Daten genommen werden, wie sie sind, dass also nicht aggregiert wird. geom...(..., stat="identity", ...)

# mini dataframe
dd <- data.frame(
    x = c( 1, 2, 3, 4, 5, 6, 7, 8),
    y = c( 3, 2, 4, 4, 6, 8, 9, 8),
    g = c(rep('m', 4), rep('f', 4))
    )
require("ggplot2")
# create a scatterplot object 
pplot <- ggplot(data=dd, aes(x=x, y=y)) + geom_point()
# add a geom smooth, representing the regression line, we exclude the default 95% confidence interval
pplot + 
  geom_smooth(method = lm, se=F)
## `geom_smooth()` using formula 'y ~ x'

# add a geom smooth, representing the regression line, 95% confidence interval included by default
pplot + 
  geom_smooth(method = lm)
## `geom_smooth()` using formula 'y ~ x'

# we can add informative descriptive lines mean and sd
ggplot(data=dd, aes(x=x, y=y)) + 
    geom_hline(yintercept=mean(dd$y), color="red") +
    geom_hline(yintercept=mean(dd$y) + sd(dd$y), color="red", alpha=0.2) + 
    geom_hline(yintercept=mean(dd$y) - sd(dd$y), color="red", alpha=0.2) + 
    geom_point(data=dd, mapping=aes(x=x, y=y))

# we can combine geom_boxplot and geom_point and geom_hline
ggplot(data=dd, aes(x=x, y=y)) + 
    geom_boxplot(data=dd, mapping=aes(x=y)) + # boxplot uses median
    geom_point() + 
    geom_hline(yintercept=mean(dd$y), color="red") # we add mean of y
## Warning: Continuous x aesthetic -- did you forget aes(group=...)?

Liniengrafiken

p <- ggplot(mry, aes(x=year, y=number, group=rating)) fill=rating? p + geom_line()

Ein Linienzug, auch unterbrochen

# mini dataframe
dd <- data.frame(
    x = c( 1, 2, 3, 4, 5, 6, 7, 8),
    y = c( 3, 2, 4, 4, 6, 8, 9, 8),
    g = c(rep('m', 4), rep('f', 4))
    )
# package ggplot2 has to be loaded
require("ggplot2")

# create a plot object with some basic information
pplot <- ggplot(data=dd, aes(x=x, y=y))
# add a line layer
pplot + geom_line()

# line interrupted
pplot <- ggplot(data=dd, aes(x=x, y=y, group=g))
pplot + geom_line()

mehrere Linien

Die darzustellenden Linien stehen in separaten Spalten im Dataframe und können verschiedene Farben haben.

# mini dataframe
dd <- data.frame(
    x  = c( 1, 2, 3, 4, 5, 6, 7, 8),
    y1 = c( 3, 2, 4, 4, 6, 8, 9, 8),
    y2 = c( 4, 5, 6, 5, 8, 9,11,14),
    g = c(rep('m', 4), rep('f', 4))
    )
# package ggplot2 has to be loaded
require("ggplot2")
# create a plot object with some basic information
pplot <- ggplot(data=dd, aes(x=x))
# add two line layers
pplot + geom_line(aes(y=y1)) + geom_line(aes(y=y2))

pplot + geom_line(aes(y=y1), color='red') + geom_line(aes(y=y2), color='blue')

# two lines interrupted
pplot <- ggplot(data=dd, aes(x=x, y=y, group=g))
pplot + geom_line(aes(y=y1), color='red') + geom_line(aes(y=y2), color='blue')

Mehrere Linien, Daten im Long-Format

Für ggplot() ist die Visualisierung eines Verlaufs oder einer Entwicklung, die häufig durch Linien symbolisiert werden, sehr viel “natürlicher” mit Daten im Long-Format realisierbar.

# mini dataframe
dd <- data.frame(
    g  = factor(c( 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3)),
    # x  = rep(c(1, 2, 3, 4, 5), 3),
    x  = c( 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
    y  = c( 3, 2, 3, 4, 6, 2, 2, 4, 3, 7, 1, 3, 5, 8, 9)
    )
# package ggplot2 has to be loaded
require("ggplot2")
# create a plot object with some basic information
pplot <- ggplot(data=dd, aes(x=x, y=y, group=g))
pplot + geom_line()

# each line with separate color
pplot + geom_line(aes(color=g))

Linien mit Punkten

# mini dataframe
dd <- data.frame(
    g  = factor(c( 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3)),
    # x  = rep(c(1, 2, 3, 4, 5), 3),
    x  = c( 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
    y  = c( 3, 2, 3, 4, 6, 2, 2, 4, 3, 7, 1, 3, 5, 8, 9)
    )
# package ggplot2 has to be loaded
require("ggplot2")
# create a plot object with some basic information
pplot <- ggplot(data=dd, aes(x=x, y=y, group=g))
# each line with separate color
pplot + geom_line(aes(color=g)) + geom_point(aes(color=g, shape = g))

# each line with different color and shape
pplot + geom_line(aes(color=g)) + geom_point(aes(color=g, shape = g))

# each line with different color and shape and a bigger size of point
pplot + geom_line(aes(color=g)) + geom_point(aes(color=g, shape = g), size=7)

Linien mit Streuungsinformation

# mini dataframe
dd <- data.frame(
    g  = factor(c( 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3)),
    # x  = factor(rep(c(1, 2, 3, 4, 5), 3)),
    x  =        c( 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
    y  =        c( 3, 2, 3, 4, 6, 2, 2, 4, 3, 7, 1, 3, 5, 8, 9),
    se =        c(.2,.3,.1,.2,.1,.3,.4,.3,.3,.4,.1,.2,.1,.1,.2)
    )
# package ggplot2 has to be loaded
require("ggplot2")
# create a plot object with some basic information
pplot <- ggplot(data=dd, aes(x=x, y=y, group=g))

# just to show that errorbars are plotted on own layer
pplot + geom_errorbar(aes(ymax = y + se, ymin=y - se), width=0.1)

# combine it with lines
pplot + geom_line(aes(color=g)) + geom_errorbar(aes(ymax = y + se, ymin=y - se), width=0.1)

# each line with different color and shape and a bigger size of point and errorbar
pplot + 
    geom_line(aes(color=g)) + 
    geom_point(aes(color=g, shape = g), size=4) + 
    geom_errorbar(aes(ymax = y + se, ymin=y - se, color=g), width=0.1)

# todo: points must not overlap

Gruppierte Daten

Am Beispiel von Scatterplots. Wir können Gruppierungsvariablen sehr intuitiv nutzen, indem wir sie dem aes() hinzufügen.

# mini dataframe with tow grouping vars
dd <- data.frame(
    x = c( 1, 2, 3, 4, 5, 6, 7, 8),
    y = c( 3, 2, 4, 4, 6, 8, 9, 8),
    g = c(rep('m', 4), rep('f', 4)),
    h = c(rep(c('A', 'B'), 4))
    )
require("ggplot2")
# we create a plot object and associate it with data
pplot <- ggplot(data=dd)
# we add aes with x and y and group g, colored differently
pplot + geom_point(aes(x, y, group=g, color=g))

# we add aes with x and y and group h, colored differently
pplot + geom_point(aes(x, y, group=h, color=h))

# we can visualize two groups combining color and shape
pplot + geom_point(aes(x, y, group=g, color=g, shape=h))

# we can mix points and lines
pplot + 
    geom_point(aes(x, y, group=g, color=g, shape=h)) +
    geom_line(aes(x, y, group=g, color=g, shape=h))
## Warning: Ignoring unknown aesthetics: shape

# or
pplot + 
    geom_point(aes(x, y, group=g, color=g, shape=h)) +
    geom_line(aes(x, y, group=h, color=h))

# use both grouping vars combined by applying interaction and line
pplot + (aes(x, y, colour=h, shape = g,
  group=interaction(g, h))) + 
  geom_point() + geom_line()

Balkendiagramme (bar plots)

Hier ein Beispiel, bei dem die Daten, insbesondere die darzustellenden Mittelwerte bereits vorliegen. Daher bekommt das normalerweise “aggregierende” geom_bar() die Angabe stat="identity"

# mini dataframe
dd <- data.frame(
    time  = c("t1", "t2", "t1", "t2"),
    group = c("f", "f", "m", "m"),
    mean  = c(1.6, 1.8, 3.5, 4.1),
    se    = c(0.1, 0.3, 0.3, 0.2)
    )
# package ggplot2 has to be loaded
require("ggplot2")

# create a plot object, define dataframe to use, add gender to differ in colour already in base plot
pplot <- ggplot(dd, x=group, y=mean, aes(group, mean, fill = time))

# create a bar plot
pplot +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_errorbar(aes(ymax = mean + se, ymin= mean - se), position = position_dodge(width=0.7), width=0.2) +
  #geom_point(stat="identity", shape=21, size=5, position=position_dodge(width=0.7), width=0.2)
  geom_point(stat="identity", shape=21, size=5, position=position_dodge(width=0.7))

# we might prefer other colors
pplot +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_errorbar(aes(ymax = mean + se, ymin= mean - se), position = position_dodge(width=0.7), width=0.2) +
  # geom_point(stat="identity", shape=21, size=5, position=position_dodge(width=0.7), width=0.2) +
  geom_point(stat="identity", shape=21, size=5, position=position_dodge(width=0.7)) +
      scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))

Grafiken auf Basis von mehreren Datenquellen und vorgegebenen Werten

ggplot Grafiken können in einer Grafik mehrere Datenquellen vom Typ Tibble/Dataframe verwenden. Wir können geom...() einen Parameter data= hinzufügen, der benutzt werden soll. Hierdurch können Rohwerte und aus anderen Berechnungen stammende Ergebnisse in einer Grafik gemeinsam verwendet werden.

Eigentlich wird hier das Konzept von ggplot() aufgeweicht. geom_errorbar() ist eigentlich eine aggregierende Funktion. Hier werden die vorgegebenen Angaben aus dd3 um Punkte eines Scatterplots “aufgezwungen” und nicht durch geom_errorbar() eigenständig berechnet. Dies geht überhaupt über den Parameter stat="identity" und zeigt die Flexibilität von ggplot()

require("ggplot2")
# define dataframe 3 groups, gender and two vars (weight and height)
dd1 <- data.frame(
  m.weight = c( 50,  55,  75,  77,  90,  98), 
  m.height = c(165, 184, 170, 179, 167, 182), 
  group = factor(c(rep(1,2),rep(2,2),rep(3,2))), 
  gender = factor(c(rep(c(1,2),3)))
  )
# we might have new weights after some treatment
dd2 <- data.frame(
  m.weight=c( 55,  57,  74,  75,  78,  88), 
  m.height=c(165, 184, 170, 179, 167, 182), 
  group=factor(c(rep(1,2),rep(2,2),rep(3,2))), 
  gender=factor(c(rep(c(1,2),3)))
  )
dd3 <- data.frame(
    m1  = mean(dd1$m.weight),
    se1 =   sd(dd1$m.weight) / sqrt(length(dd1$m.weight)),
    m2  = mean(dd2$m.weight),
    se2 =   sd(dd2$m.weight) / sqrt(length(dd2$m.weight))
)
# we do a plot of t1
( pplot <- ggplot() +  
  geom_point(data = dd1, aes(x=m.height, y=m.weight, shape=group))
)

# we add t2
( pplot2 <- pplot + 
  geom_point(data=dd2, aes(m.height, m.weight, shape=group, color='red'), show.legend=F) 
)

# we add something of dd3
( pplot3 <- pplot2 + 
  geom_point(data=dd3, stat='identity', aes(160, m1, size=10), show.legend=F) +
    geom_errorbar(data=dd3, stat='identity', aes(x=160, ymax = m1 + se1, ymin=m1 - se1), show.legend=F) + 
  geom_point(data=dd3, stat='identity', aes(161, m2, size=10, color='red'), show.legend=F) +
    geom_errorbar(data=dd3, stat='identity', aes(x=161, ymax = m2 + se2, ymin=m2 - se2, color='red'), show.legend=F)
)

# erase data to keep environment clean
rm(dd1)
rm(dd2)
rm(dd3)

Beispiele und Aufgaben

Ein Beispiel mit virtuellen Daten zu Reaktionszeiten und P300 (EEG) html

Ein paar Experimente und Beispielcode: bmi_graphics html

Beispielgrafiken: body_comarison_graphics html

Aufgaben variieren

  • “spielen” Sie in den obigen Versteh-Beispielen, indem Sie Daten verändern und den Effekt auf die erzeugten Grafiken beobachten

  • “spielen” Sie in den obigen Versteh-Beispielen mit den Parametern von ggplot

  • gestalten Sie die Beispielgrafiken mit zusätzlichen Hervorhebungen, Erklärungen, Markierungen etc. aus

Aufgabe Datensatz “df_dplyr.txt”

Erstellen Sie für den Beispielatensatz df_dplyr.txt - ein paar Scatterplots (v1, v2, v3) - v1 … v3 als Verläufe in x-Richtung - Boxplot für Geschlecht, Gruppe - Bargraph für Geschlecht, Gruppe - … mit Errorbars - … mit Vorberechnung der aggregierten Werte z. B. unter Anwendung von summarySE() - fassen Sie die Variablen v1 … v3 als Messwiederholungen auf und erstellen Sie eine Grafik, in der der Verlauf gruppenspezifisch ausgegeben wird

require(tidyverse)
## Loading required package: tidyverse
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble  3.1.0     ✓ dplyr   1.0.5
## ✓ readr   1.4.0     ✓ stringr 1.4.0
## ✓ purrr   0.3.4     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::arrange()    masks plyr::arrange()
## x readr::col_factor() masks scales::col_factor()
## x purrr::compact()    masks plyr::compact()
## x dplyr::count()      masks plyr::count()
## x purrr::discard()    masks scales::discard()
## x dplyr::failwith()   masks plyr::failwith()
## x dplyr::filter()     masks stats::filter()
## x dplyr::id()         masks plyr::id()
## x dplyr::lag()        masks stats::lag()
## x dplyr::mutate()     masks plyr::mutate()
## x dplyr::rename()     masks plyr::rename()
## x dplyr::summarise()  masks plyr::summarise()
## x dplyr::summarize()  masks plyr::summarize()
dd <- read_delim("http://md.psych.bio.uni-goettingen.de/mv/data/div/df_dplyr.txt", delim="\t")
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   subj = col_double(),
##   gender = col_character(),
##   age = col_double(),
##   grp = col_double(),
##   v1 = col_double(),
##   v2 = col_double(),
##   v3 = col_double()
## )
# or
dd <- read_tsv("http://md.psych.bio.uni-goettingen.de/mv/data/div/df_dplyr.txt")
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   subj = col_double(),
##   gender = col_character(),
##   age = col_double(),
##   grp = col_double(),
##   v1 = col_double(),
##   v2 = col_double(),
##   v3 = col_double()
## )

Aufgabe economics

In R ist ein Datensatz über ökonomische Verlaufsdaten der USA hinterlegt.

Achtung:

Der Zahlenname Billion steht im deutschen Sprachgebrauch für die Zahl 1000 Milliarden oder 1.000.000.000.000 = 1012, im Dezimalsystem also für eine Eins mit 12 Nullen. 1000 Billionen ergeben eine Billiarde. Der Vorsatz für Maßeinheiten für den Faktor eine Billion ist Tera mit dem Zeichen T. Abgekürzt wird sie mit Bio. oder Bill., wobei Letzteres mit Billiarde verwechselt werden kann.

Das US-amerikanische billion hingegen entspricht der deutschen Milliarde.

  • zeichnen Sie den Verlauf der Arbeitslosenzahlen über die Jahre
  • zeichnen Sie zusätzlich einen Smoother mit ein, um den Langzeit-Trend zu visualisieren
help(economics)
# we make economics accessible by a shorter name, df
df <- economics

pp <- ggplot(data = economics, aes(x = date, y = unemploy))
pp <- pp + geom_line()
pp <- pp + geom_smooth()

pp
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Beispiel l/100km und MpG

1 L/100km entspricht \(100 * 3.79/1.61 = 235.4 mpg\).

  • 1 Gallone = 3.79 Liter (L)
  • 1 Meile = 1.61 Kilometer (km)

mpg -> l/100

\(l/100km = 100 / (mpg * 1.6) * 3.7\)

require(ggplot2)
?mpg
dd <- mpg

require(psych)
## Loading required package: psych
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:scales':
## 
##     alpha, rescale
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
psych::describe(dd)
##               vars   n    mean    sd median trimmed   mad    min  max range
## manufacturer*    1 234    7.76  5.13    6.0    7.68  5.93    1.0   15  14.0
## model*           2 234   19.09 11.15   18.5   18.98 14.08    1.0   38  37.0
## displ            3 234    3.47  1.29    3.3    3.39  1.33    1.6    7   5.4
## year             4 234 2003.50  4.51 2003.5 2003.50  6.67 1999.0 2008   9.0
## cyl              5 234    5.89  1.61    6.0    5.86  2.97    4.0    8   4.0
## trans*           6 234    5.65  2.88    4.0    5.53  1.48    1.0   10   9.0
## drv*             7 234    1.67  0.66    2.0    1.59  1.48    1.0    3   2.0
## cty              8 234   16.86  4.26   17.0   16.61  4.45    9.0   35  26.0
## hwy              9 234   23.44  5.95   24.0   23.23  7.41   12.0   44  32.0
## fl*             10 234    4.63  0.70    5.0    4.77  0.00    1.0    5   4.0
## class*          11 234    4.59  1.99    5.0    4.64  2.97    1.0    7   6.0
##                skew kurtosis   se
## manufacturer*  0.21    -1.63 0.34
## model*         0.11    -1.23 0.73
## displ          0.44    -0.91 0.08
## year           0.00    -2.01 0.29
## cyl            0.11    -1.46 0.11
## trans*         0.29    -1.65 0.19
## drv*           0.48    -0.76 0.04
## cty            0.79     1.43 0.28
## hwy            0.36     0.14 0.39
## fl*           -2.25     5.76 0.05
## class*        -0.14    -1.52 0.13
require(tidyverse)
# we recalculate miles per gallon into liters per 100 km and save it in an additional column
dd$ctl100km <- 100 / (dd$cty * 1.6) * 3.7
dd$hwl100km <- 100 / (dd$hwy * 1.6) * 3.7
# we generate column eco which represents the order from most economic to least economic consumption
dd <- dd %>% arrange(ctl100km)
dd$eco <- 1:nrow(dd)

# we plot city consumption and hiway consumption for the manufacturers
dd %>% ggplot(aes(x=manufacturer, y=ctl100km, color="red")) + geom_point() + geom_point(aes(y=hwl100km, color="blue"))

# we plot average city consumption for the manufacturers
dd %>% ggplot(aes(x=manufacturer, y=ctl100km, color=manufacturer)) + stat_summary(fun.y = mean, geom="point") +
  stat_summary(fun.data = mean_cl_normal, geom = "errorbar", width=0.2, size=1)
## Warning: `fun.y` is deprecated. Use `fun` instead.

# we aggregate data to get a tibble with average consumption per manufacturer (row)
dd %>% dplyr::group_by(manufacturer) %>% dplyr::summarise(ct_m=mean(ctl100km), ct_se=sd(ctl100km)/sqrt(n())) -> dd.m
dd.m <- dd.m %>% dplyr::mutate(upper = ct_m + ct_se, lower = ct_m - ct_se) %>% dplyr::arrange(ct_m)
# we generate column eco which represents the order from most economic to least economic manufacturer in consumption
dd.m$eco <- 1:nrow(dd.m)

dd.m$manuf <- factor(dd.m$manufacturer)

# consumption ordered by manufacturer
dd.m %>% ggplot(aes(x=manufacturer[15:1], y=ct_m, color=manufacturer)) + geom_point(size=3) + 
  geom_errorbar(mapping=aes(x=manufacturer[15:1], ymin=upper, ymax=lower), width=0.2, size=1) 

# consumption ordered by consumption
dd.m %>% ggplot(aes(x=reorder(manuf, eco), y=ct_m, color=reorder(manuf, eco))) + 
  geom_point(size=3) + 
  geom_errorbar(mapping=aes(x=reorder(manuf, eco), ymin=upper, ymax=lower), width=0.2, size=1) 

Interpolieren

… bei missing values in Messwiederholungsverläufen,

Eine Erhebung über 7 Jahre hat aus politischen Gründen in den Jahren 4 und 5 nicht stattgefunden. Die beiden fehlenden Jahre sollen durch geeignete Werte auf individueller Basis geschätzt werden.

require(tidyverse)
dd <-tibble(
  subj = as.factor(c(1,2,3,4,5)),
  y1   = c( 2,  0,  5,  4,  7),
  y2   = c( 6,  2,  7, 12,  9),
  y3   = c( 7,  9,  9, 15, 15),
  y4   = c(NA, NA, NA, NA, NA),
  y5   = c(NA, NA, NA, NA, NA),
  y6   = c(14, 18, 15, 22, 25),
  y7   = c(18, 22, 19, 29, 23)
)
# we convert dd to long format
dd.l <- dd %>% tidyr::gather(year, score, y1:y7) %>% dplyr::arrange(subj)
# and show a graph with the gap between the missing years
dd.l %>% ggplot2::ggplot(aes(x=year, y=score, group=subj, color=subj)) + ggplot2::geom_line() + ggplot2::geom_point(size=5) 
## Warning: Removed 10 rows containing missing values (geom_point).

# we interpolate the missings
dd %>% dplyr::mutate(diff_3_6 = y6 - y3, y4 = y3 + diff_3_6/3, y5 = y6 - diff_3_6 / 3) -> dd
# we convert dd to long format
dd.l <- dd %>% tidyr::gather(year, score, y1:y7) %>% dplyr::arrange(subj)
# and show a graph with the gap between the missing years
dd.l %>% ggplot2::ggplot(aes(x=year, y=score, group=subj, color=subj)) + ggplot2::geom_line() + ggplot2::geom_point(size=5) 

# btw: we could also think of an individual regression line

Versuche stat_summary

require(ggplot2)
year_plot <- ggplot(mpg, aes(x = class, y = cty))
year_plot + stat_summary(fun.y = mean, geom = "point") + 
  stat_summary(fun.y = mean, geom = "line", aes(group = 1)) +
  stat_summary(fun.data = mean_cl_normal, geom = "errorbar", width = 0.2) +
  labs(x = "Art des Autos",
       y = "Miles per Gallon (Stadt)",
       title = "Miles per Gallon in der Stadt nach Art des Autos")
## Warning: `fun.y` is deprecated. Use `fun` instead.

## Warning: `fun.y` is deprecated. Use `fun` instead.

mpg_data <- mpg
year_plot <- ggplot(mpg, aes(x = class, y = cty))
year_plot + stat_summary(fun.y = mean, geom = "point") + 
  stat_summary_bin(fun.y = mean, geom = "line")
## Warning: `fun.y` is deprecated. Use `fun` instead.

## Warning: `fun.y` is deprecated. Use `fun` instead.
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

Teilaufgabe sheet_plots

Auf Wunsch der Studierenden ein Abschnitt, wie ihn Johannes Brachem vorgestellt hat am 7.5.2020

library(tidyverse)
# tm <- read_delim("text_messages.dat", delim = "\t")
tm <- read_delim("https://owncloud.gwdg.de/index.php/s/d1QBJpKEpqhPIa9/download", delim = "\t")
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   Group = col_character(),
##   Baseline = col_double(),
##   Six_months = col_double()
## )
tm$Group %>% unique()
## [1] "Text Messagers" "Controls"
tm_long <- tm %>% gather(Baseline, Six_months, key = "time", value = "score")
p1 <- ggplot(tm_long, aes(x = time, y = score, color = Group))
p1 + 
  stat_summary(fun = "mean",      # Mittelwerte berechnen
               geom = "point",    # Als Punkte anzeigen lassen
               size = 2.5,        # Größe verändern
               aes(shape = Group)
  ) +
  stat_summary(fun.data = mean_cl_boot,
               geom = "errorbar",
               width = 0.2
               ) +
  stat_summary(fun = "mean",
               geom = "line",
               aes(group = Group, linetype = Group)
               ) +
  scale_linetype_manual(values = c(5, 4)) +
  
  labs(x = "Zeit", 
       y = "Grammatik-Score", 
       title = "Plot-Titel",
       color = "Gruppe",
       shape = "Gruppe",
       linetype = "Gruppe"
       ) +
  NULL

Check

  • habe ich das Prinzip hinter stat="identity" verstanden?

  • habe ich verstanden, dass vorgegebene, bereits aggregierte Werte ggplot() untergeschoben werden?

Version: 22 April, 2021 06:52