Data Science 1 - Programmieren & Visualisieren
Saskia Otto
Universität Hamburg, IMF
Wintersemester 2022/2023
par()
und layout()
nichtviewport()
und grid.layout()
in dem Paket gridgrid.arrange()
in dem Paket gridExtra → siehe auch die gridExtra Vignetteplot_grid()
und draw_plot()
in dem Paket cowplot → siehe auch die cowplot WebsiteJede Herangehensweise wird mit 3 verschiedenen Diagramme vom bshydro15
Datensatz demonstriert:
summer <- bshydro15 |>
filter(pres <= 5, month %in% c("May", "Jun", "Jul", "Aug"))
a <- summer |>
select(sampling_id, month) |>
distinct() |>
ggplot(aes(x = month)) +
geom_bar(aes(fill = month)) +
guides(fill = "none") +
scale_fill_brewer(palette = "Set1") +
guides(x = guide_axis(angle = 90)) +
theme_classic()
sss_sum <-summer |>
# Bildung des Temperaturmittelwerts über die 5m
group_by(ices_sd, station, lat, long, date_time, month, day) |>
summarise(psal = mean(psal, na.rm = TRUE)) |>
ungroup() |>
drop_na()
b <- ggplot(sss_sum, aes(x = long, y = psal, col = ices_sd)) +
geom_point() +
scale_colour_brewer(palette = "Paired") +
guides(colour = "none") +
theme_classic()
c <- sst_sum |>
filter(month %in% c("May", "Aug")) |>
ggplot(aes(long,lat))+
geom_point(aes(colour = temp)) +
scale_colour_gradient(low = "white", high = "red") +
facet_grid(. ~ month) +
theme_classic()
→ mit viewport()
Um ein kleines Diagramm in ein Hauptdiagramm einzubetten…
viewport()
Funktion, wo im Koordinatensystem des Hauptdiagramms das kleinere Diagramm abgebildet werden soll, und speichern es als Objekt ab.print()
Funktion, wobei das viewport Objekt dem vp Argument zugewiesen wird:→ mit grid.arrange()
→ eigene Aufteilung mit arrangeGrob()
zusätzlich
arrangeGrob()
beim Auflisten der Plotobjekte.→ noch flexibler als die Funktion arrangeGrob()
ist das Argument layout_matrix:
[,1] [,2] [,3]
[1,] 1 2 2
[2,] 3 3 3
6 Rasterzellen sind in der Matrix spezifiziert:
theme_classic()
), verschiedene Schriftgrößenplot_grid()
ist eine Kurzform mit limitierten Einstellungen:ggdraw()
→ initialisiert eine leere Zeichenleinwanddraw_plot()
→ platziert eine einzelnen Plot auf die Leinwanddraw_plot_label()
→ fügt die Beschriftungen zu den Diagrammen (voreingestellt ist die obere linke Ecke)ggsave()
(in ‘ggplot2’) kann verwendet werden um ‘ggplots’ als PDF- oder PNG-Datei zu speichern.save_plot()
(in ‘cowplot’)
Bildquelle: United States Geological Survey (CC0-Lizenz)
Bildquelle: Curth 2015, Masterarbeit, FH Hagenburg
Bildquelle: Wikipedia (CC-BY-SA 4.0 Lizenz)
Bildquelle: Wikipedia (CC-BY-SA 4.0 Lizenz)
Bildquelle: Curth 2015, Masterarbeit, FH Hagenburg
Bildquelle: Greg J. Schmidt, Misako Nishino und John Kartes. Density Gradient Map Samples Produced From BONAP’s Floristic Synthesis
# Weltkarte 1 (Atlantik im Zentrum)
world <- map_data(map = 'world')
# Deutschland aus Weltkarte beim Abgreifen filtern
germany <- map_data(map = 'world', region = 'Germany')
str(germany)
'data.frame': 568 obs. of 6 variables:
$ long : num 14.2 14.2 14 13.9 13.9 ...
$ lat : num 53.9 53.9 53.9 53.9 53.9 ...
$ group : num 1 1 1 1 1 1 1 1 1 1 ...
$ order : int 1 2 3 4 5 6 7 8 9 10 ...
$ region : chr "Germany" "Germany" "Germany" "Germany" ...
$ subregion: chr "Usedom" "Usedom" "Usedom" "Usedom" ...
→ geom_polygon()
→ + geom_point()
→ + borders()
→ + coord_fixed(ratio = 1.3)
→ + coord_map()
Eine recht ansprechende Projektion ist die orthografische Azimutalprojektion welche den Nordpol im Zentrum hat:
Beispiel für eine Choroplethenkarte
# Einfügen neuer Daten in 'world' data frame
world_wood <- dplyr::left_join(world, wooded_area, by = c("region" = "country"))
# Darstellung der Europakarte mit neuen Daten
wood_map <- ggplot(world_wood, aes(x = long, y = lat)) +
geom_polygon(aes(group = group, fill = X2020)) + # fill = X2020 ist neu
# Anpassung der kontinuerlichen Farbskala und Legende
scale_fill_gradient2(low = "#edf8e9", mid = "#74c476", high = "#005a32",
midpoint = 10000, guide = "legend", n.breaks = 10) +
labs(x = "Längengrad", y = "Breitengrad",
fill = "Bewaldete Fläche in \n2020 (in 1000ha)",
caption = "Quelle: Eurostat Datenbank (https://ec.europa.eu/eurostat/web/main/home)") +
coord_map(projection = 'orthographic', orientation = c(55, 10,0),
xlim = c(-10, 30), ylim = c(35,70)) +
theme_minimal() +
theme(panel.border = element_rect(color = "black", fill = NA, linewidth = .5))
wood_map
→ ggmap()
im ggmap Paket
library(ggmap)
# Europa-Ausschnitt wählen
euro_bbox <- c(left = -10, bottom = 35,
right = 30, top = 65)
# Stamen Karte abgreifen mit
# get_stamenmap()
stm <- get_stamenmap(
bbox = euro_bbox,
zoom = 5,
maptype = 'terrain'
) # alternativ: 'watercolor', 'toner'
# Karte plotten mit ggmap()
ggmap(stm) +
geom_point(
data = european_capitals,
mapping = aes(x = long, y = lat),
colour = 'red', size = 2
)
geom_sf()
und coord_sf()
für die Koordinatentransformation.Link zur Website: https://paleolimbot.github.io/ggspatial/
library(ggplot2)
library(ggspatial)
load_longlake_data()
ggplot() +
# lädt Hintergrundkartenkacheln aus einer Kachelquelle
annotation_map_tile(zoomin = -1) +
# annotation_spatial()-Schichten trainieren die Skalen nicht,
# so dass die Daten zentral bleiben
annotation_spatial(longlake_roadsdf, size = 2, col = "black") +
annotation_spatial(longlake_roadsdf, size = 1.6, col = "white") +
# Rasterebenen trainieren Skalen und werden automatisch projiziert
layer_spatial(longlake_depth_raster, aes(colour = after_stat(band1))) +
# fehlende Werte nicht anzeigen
scale_fill_viridis_c(na.value = NA) +
# layer_spatial bildet die Skalen aus
layer_spatial(longlake_depthdf, aes(fill = DEPTH_M)) +
# hinzufügen eines Maßstabsbalken
annotation_scale(location = "tl") +
# hinzufügen eines Nordpfeils
annotation_north_arrow(location = "br", which_north = "true")
Link zur Website: https://r-tmap.github.io/tmap/
library(tmap)
# Beispieldaten laden
data(World, metro, rivers, land)
tmap_mode("plot")
## tmap-Modus auf Plotten eingestellt
tm_shape(land) +
tm_raster("elevation", palette = terrain.colors(10)) +
tm_shape(World) +
tm_borders("white", lwd = .5) +
tm_text("iso_a3", size = "AREA") +
tm_shape(metro) +
tm_symbols(col = "red", size = "pop2020", scale = 1.5) +
tm_legend(show = FALSE)
Link zur Website: https://riatelab.github.io/mapsf/
library(mapsf)
# Beispieldaten laden
mtq <- mf_get_mtq()
# Theme festlegen
mf_init(x = mtq, theme = "candy", expandBB = c(0, 0, 0, .15))
# Schatten erzeugen
mf_shadow(mtq, add = TRUE)
# Gemeinden plotten
mf_map(mtq, add = TRUE)
# Punktsymbole mit Choroplethenfärbung
mf_map(
x = mtq,
var = c("POP", "MED"),
type = "prop_choro",
border = "grey50",
lwd = 1,
leg_pos = c("topright", "right"),
leg_title = c("Population", "Median\nIncome\n(in euros)"),
breaks = "equal",
nbreaks = 4,
pal = "Greens",
leg_val_rnd = c(0, -2),
leg_frame = c(TRUE, TRUE)
)
# Layout
mf_layout(
title = "Population & Wealth in Martinique, 2015",
credits = paste0(
"Sources: Insee and IGN, 2018\n",
"mapsf ",
packageVersion("mapsf")
),
frame = TRUE
)
Mithilfe des Softwareentwicklungs-Framework htmlwidgets gibt es nun R Schnittstellen für JavaScript (JS) Visualisierungsbibliotheken wie z.B
Alle Pakete arbeiten mit dem Pipe-Operator!
→ leaflet()
und addTiles()
→ setView()
→ addProviderTiles()
Infos zu Stamen-Karten: http://maps.stamen.com/
→ addProviderTiles()
[1] "OpenStreetMap"
[2] "OpenStreetMap.Mapnik"
[3] "OpenStreetMap.DE"
[4] "OpenStreetMap.CH"
[5] "OpenStreetMap.France"
[6] "OpenStreetMap.HOT"
[7] "OpenStreetMap.BZH"
[8] "OpenSeaMap"
[9] "OpenPtMap"
[10] "OpenTopoMap"
[11] "OpenRailwayMap"
[12] "OpenFireMap"
[13] "SafeCast"
[14] "Thunderforest"
[15] "Thunderforest.OpenCycleMap"
[16] "Thunderforest.Transport"
[17] "Thunderforest.TransportDark"
[18] "Thunderforest.SpinalMap"
[19] "Thunderforest.Landscape"
[20] "Thunderforest.Outdoors"
[21] "Thunderforest.Pioneer"
[22] "Thunderforest.MobileAtlas"
[23] "Thunderforest.Neighbourhood"
[24] "OpenMapSurfer"
[25] "OpenMapSurfer.Roads"
[26] "OpenMapSurfer.Hybrid"
[27] "OpenMapSurfer.AdminBounds"
[28] "OpenMapSurfer.ContourLines"
[29] "OpenMapSurfer.Hillshade"
[30] "OpenMapSurfer.ElementsAtRisk"
[31] "Hydda"
[32] "Hydda.Full"
[33] "Hydda.Base"
[34] "Hydda.RoadsAndLabels"
[35] "MapBox"
[36] "Stamen"
[37] "Stamen.Toner"
[38] "Stamen.TonerBackground"
[39] "Stamen.TonerHybrid"
[40] "Stamen.TonerLines"
[41] "Stamen.TonerLabels"
[42] "Stamen.TonerLite"
[43] "Stamen.Watercolor"
[44] "Stamen.Terrain"
[45] "Stamen.TerrainBackground"
[46] "Stamen.TerrainLabels"
[47] "Stamen.TopOSMRelief"
[48] "Stamen.TopOSMFeatures"
[49] "TomTom"
[50] "TomTom.Basic"
[51] "TomTom.Hybrid"
[52] "TomTom.Labels"
[53] "Esri"
[54] "Esri.WorldStreetMap"
[55] "Esri.DeLorme"
[56] "Esri.WorldTopoMap"
[57] "Esri.WorldImagery"
[58] "Esri.WorldTerrain"
[59] "Esri.WorldShadedRelief"
[60] "Esri.WorldPhysical"
[61] "Esri.OceanBasemap"
[62] "Esri.NatGeoWorldMap"
[63] "Esri.WorldGrayCanvas"
[64] "OpenWeatherMap"
[65] "OpenWeatherMap.Clouds"
[66] "OpenWeatherMap.CloudsClassic"
[67] "OpenWeatherMap.Precipitation"
[68] "OpenWeatherMap.PrecipitationClassic"
[69] "OpenWeatherMap.Rain"
[70] "OpenWeatherMap.RainClassic"
[71] "OpenWeatherMap.Pressure"
[72] "OpenWeatherMap.PressureContour"
[73] "OpenWeatherMap.Wind"
[74] "OpenWeatherMap.Temperature"
[75] "OpenWeatherMap.Snow"
[76] "HERE"
[77] "HERE.normalDay"
[78] "HERE.normalDayCustom"
[79] "HERE.normalDayGrey"
[80] "HERE.normalDayMobile"
[81] "HERE.normalDayGreyMobile"
[82] "HERE.normalDayTransit"
[83] "HERE.normalDayTransitMobile"
[84] "HERE.normalDayTraffic"
[85] "HERE.normalNight"
[86] "HERE.normalNightMobile"
[87] "HERE.normalNightGrey"
[88] "HERE.normalNightGreyMobile"
[89] "HERE.normalNightTransit"
[90] "HERE.normalNightTransitMobile"
[91] "HERE.reducedDay"
[92] "HERE.reducedNight"
[93] "HERE.basicMap"
[94] "HERE.mapLabels"
[95] "HERE.trafficFlow"
[96] "HERE.carnavDayGrey"
[97] "HERE.hybridDay"
[98] "HERE.hybridDayMobile"
[99] "HERE.hybridDayTransit"
[100] "HERE.hybridDayGrey"
[101] "HERE.hybridDayTraffic"
[102] "HERE.pedestrianDay"
[103] "HERE.pedestrianNight"
[104] "HERE.satelliteDay"
[105] "HERE.terrainDay"
[106] "HERE.terrainDayMobile"
[107] "FreeMapSK"
[108] "MtbMap"
[109] "CartoDB"
[110] "CartoDB.Positron"
[111] "CartoDB.PositronNoLabels"
[112] "CartoDB.PositronOnlyLabels"
[113] "CartoDB.DarkMatter"
[114] "CartoDB.DarkMatterNoLabels"
[115] "CartoDB.DarkMatterOnlyLabels"
[116] "CartoDB.Voyager"
[117] "CartoDB.VoyagerNoLabels"
[118] "CartoDB.VoyagerOnlyLabels"
[119] "CartoDB.VoyagerLabelsUnder"
[120] "HikeBike"
[121] "HikeBike.HikeBike"
[122] "HikeBike.HillShading"
[123] "BasemapAT"
[124] "BasemapAT.basemap"
[125] "BasemapAT.grau"
[126] "BasemapAT.overlay"
[127] "BasemapAT.highdpi"
[128] "BasemapAT.orthofoto"
[129] "nlmaps"
[130] "nlmaps.standaard"
[131] "nlmaps.pastel"
[132] "nlmaps.grijs"
[133] "nlmaps.luchtfoto"
[134] "NASAGIBS"
[135] "NASAGIBS.ModisTerraTrueColorCR"
[136] "NASAGIBS.ModisTerraBands367CR"
[137] "NASAGIBS.ViirsEarthAtNight2012"
[138] "NASAGIBS.ModisTerraLSTDay"
[139] "NASAGIBS.ModisTerraSnowCover"
[140] "NASAGIBS.ModisTerraAOD"
[141] "NASAGIBS.ModisTerraChlorophyll"
[142] "NLS"
[143] "JusticeMap"
[144] "JusticeMap.income"
[145] "JusticeMap.americanIndian"
[146] "JusticeMap.asian"
[147] "JusticeMap.black"
[148] "JusticeMap.hispanic"
[149] "JusticeMap.multi"
[150] "JusticeMap.nonWhite"
[151] "JusticeMap.white"
[152] "JusticeMap.plurality"
[153] "Wikimedia"
[154] "GeoportailFrance"
[155] "GeoportailFrance.parcels"
[156] "GeoportailFrance.ignMaps"
[157] "GeoportailFrance.maps"
[158] "GeoportailFrance.orthos"
[159] "OneMapSG"
[160] "OneMapSG.Default"
[161] "OneMapSG.Night"
[162] "OneMapSG.Original"
[163] "OneMapSG.Grey"
[164] "OneMapSG.LandLot"
→ addMarkers()
, addCircleMarkers()
und addRectangles()
lng <- 9.9789
lat <- 53.5675
m <- leaflet() |>
addTiles() |>
setView(lng = lng, lat = lat, zoom = 20) |>
# Rechteck:
addRectangles(
lng1 = 9.978, lat1 = 53.5671,
lng2 = 9.9795, lat2 = 53.5679,
fillColor = "transparent") |>
# sog. Icon Markers:
addMarkers(lng = lng, lat = lat,
popup = "Eingang des Instituts für Zell- und Systembiologie der Tiere (IZS)",
label = "IZS") |>
# Kreismarkierung:
addCircleMarkers(lng = 9.97925, lat = 53.56735,
popup = "Gr. Hörsaal der Zoologie", label = "Unser Standort",
color = "red", radius = 35, stroke = TRUE, opacity = 0.5,
weight = 3, fill = TRUE, fillColor = "red", fillOpacity = 0.2)
m
Zum Speichern gibt es 2 Möglichkeiten:
saveWidget()
Funktion im Paket htmlwidgets die Karte als HTML-Datei speichern und mit webshot()
aus dem webshot2 Paket diese zu PNG umwandeln:ggplotply()
können ggplot2 Grafiken ganz einfach in interaktive Diagramme umgewandeln werden!Anpassungen über das 'tooltip' Argument
subplot()
im plotly Paket ist ähnlich wie die Funktion grid.arrange()
Funktion aus dem gridExtra Paketp_bill <- ggplotly(gg_bill)
# Erstelle zweites Diagramm
gg_weight <- drop_na(penguins, sex) |>
ggplot(aes(x = species, y = body_mass_g))+
geom_boxplot(aes(fill = sex))
p_weight <- ggplotly(gg_weight)
# In einer Zeile anordnen und relative Breite ändern, Legende ausblenden
subplot(p_bill, gg_weight, nrows = 1, widths = c(0.7, 0.3)) |>
hide_legend()
Zum Speichern gibt es bei plotly 3 Möglichkeiten:
saveWidget()
und webshot()
Funktionen wie bei leaflet:ggplotly()
sind begrenzt.library(reshape2)
library(tidyverse)
library(tidymodels)
library(plotly)
library(kernlab)
library(pracma) # Für meshgrid()
mesh_size <- .02
margin <- 0
X <- iris |> select(Sepal.Width, Sepal.Length)
y <- iris |> select(Petal.Width)
model <- svm_rbf(cost = 1.0) |>
set_engine("kernlab") |>
set_mode("regression") |>
fit(Petal.Width ~ Sepal.Width + Sepal.Length, data = iris)
x_min <- min(X$Sepal.Width) - margin
x_max <- max(X$Sepal.Width) - margin
y_min <- min(X$Sepal.Length) - margin
y_max <- max(X$Sepal.Length) - margin
xrange <- seq(x_min, x_max, mesh_size)
yrange <- seq(y_min, y_max, mesh_size)
xy <- meshgrid(x = xrange, y = yrange)
xx <- xy$X
yy <- xy$Y
dim_val <- dim(xx)
xx1 <- matrix(xx, length(xx), 1)
yy1 <- matrix(yy, length(yy), 1)
final <- cbind(xx1, yy1)
pred <- model |>
predict(final)
pred <- pred$.pred
pred <- matrix(pred, dim_val[1], dim_val[2])
fig <- plot_ly(iris, x = ~Sepal.Width, y = ~Sepal.Length, z = ~Petal.Width ) |>
add_markers(size = 5) |>
add_surface(x=xrange, y=yrange, z=pred, alpha = 0.65, type = 'mesh3d', name = 'pred_surface')
fig
Bei weiteren Fragen: saskia.otto(at)uni-hamburg.de
Diese Arbeit is lizenziert unter einer Creative Commons Attribution-ShareAlike 4.0 International License mit Ausnahme der entliehenen und mit Quellenangabe versehenen Abbildungen.
Kurswebseite: Data Science 1