Bölüm 3 Highcharter Kütüphanesi

highcharter kütüphanesi, JavaScript dilinde bulunan highcharts paketinin R diline uyarlanmış halidir.

3.1 Neden highcharter?

  • Fonksiyonellik
  • İnteraktif veri görselleştirme
  • Karşılaştırma grafikleri
  • JS gücü
# install.packages("highcharter")
library(highcharter)
#> Registered S3 method overwritten by 'quantmod':
#>   method            from
#>   as.zoo.data.frame zoo

3.1.1 Serpilme Diyagramı

# install.packages("palmerpenguins")
library(palmerpenguins)
data(penguins, package = "palmerpenguins") 
hchart(
  penguins,
  "scatter",
  hcaes(x = flipper_length_mm, y = bill_length_mm, group = species)
)
Created with Highcharts 9.3.1flipper_length_mmbill_length_mmAdelieChinstrapGentoo1801902002102202303035404550556065

3.1.2 Histogram

set.seed(1)
data = data.frame(
        cinsiyet = factor(rep(c("Kadin", "Erkek"), each=100)),
        kilo = c(rnorm(100, 55), rnorm(100, 58))
        )
data %>% head() %>% kable()
cinsiyet kilo
Kadin 54.37355
Kadin 55.18364
Kadin 54.16437
Kadin 56.59528
Kadin 55.32951
Kadin 54.17953
hchart(
  data$kilo, 
  color = "red", name = "Kilo"
  )
Created with Highcharts 9.3.1Kilo5253545556575859606101020304050

3.1.3 Bar grafiği

library(gapminder)
gapminder%>%
       dplyr::filter(year == 2007)%>%
        dplyr::arrange(-pop) %>%
hchart( type = "column", #type = "bar" olursa yatay olur
        hcaes(x = country, y = pop),
        color ='red')
Created with Highcharts 9.3.1countrypopChinaPakistanPhilippinesTurkeyUnited KingdomSouth AfricaTanzaniaAfghanistanIraqGhanaMozambiqueNetherlandsMalawiSenegalPortugalSerbiaSomaliaAustriaHong Kong, ChinaJordanSlovak RepublicBosnia and HerzegovinaIrelandAlbaniaLiberiaLesothoGabonComorosIceland0250M500M750M1 000M1 250M1 500M

3.1.4 Çizgi grafiği

data(economics_long, package = "ggplot2")

economics_long2 <- dplyr::filter(economics_long, variable %in% c("pop", "uempmed", "unemploy"))

economics_long2 %>% head() %>% kable()
date variable value value01
1967-07-01 pop 198712 0.0000000
1967-08-01 pop 198911 0.0016353
1967-09-01 pop 199113 0.0032953
1967-10-01 pop 199311 0.0049223
1967-11-01 pop 199498 0.0064590
1967-12-01 pop 199657 0.0077656
hchart(economics_long2, "line", hcaes(x = date, y = value01, group = variable))
Created with Highcharts 9.3.1datevalue01popuempmedunemploy197019751980198519901995200020052010201500.20.40.60.811.2
highchart() |>
  hc_add_series(data = sample(1:12)) |> 
  hc_add_series(data = sample(1:12) + 10) |> 
  hc_tooltip(
    # tooltip üzerine çizgi ekler (daha iyi takip edebilmek için)
    crosshairs = TRUE,
    # aynı anda tüm değerleri görebilmek için
    sort = TRUE
    ) 
Created with Highcharts 9.3.1Series 1Series 202468100510152025

** Farklı özellikler için highcharts sitesinden yararlanılabilir: ** highcharts dataLabels

3.1.5 Dağılım grafiği

density(data$kilo)
#> 
#> Call:
#>  density.default(x = data$kilo)
#> 
#> Data: data$kilo (200 obs.);  Bandwidth 'bw' = 0.5315
#> 
#>        x               y            
#>  Min.   :51.19   Min.   :5.707e-05  
#>  1st Qu.:53.87   1st Qu.:1.348e-02  
#>  Median :56.55   Median :8.380e-02  
#>  Mean   :56.55   Mean   :9.326e-02  
#>  3rd Qu.:59.22   3rd Qu.:1.697e-01  
#>  Max.   :61.90   Max.   :2.025e-01
hchart(
  density(data$kilo), 
  type = "area", name = "Kilo"
  )
Created with Highcharts 9.3.1Kilo52545658606200.050.10.150.20.25
kadin <- data %>% filter(cinsiyet == "Kadin")
erkek <- data %>% filter(cinsiyet == "Erkek")
hchart(
  density(erkek$kilo), type = "area", 
   name = "Erkek"
  ) %>%
  hc_add_series(
    density(kadin$kilo), type = "area",
    name = "Kadın"
    )
Created with Highcharts 9.3.1ErkekKadın5253545556575859606100.10.20.30.40.5

3.1.6 Kutu grafiği

library(readr)
# Verinin yüklenmesi ve hazırlığı
df <-
  read_csv(
    "https://raw.githubusercontent.com/mekhatria/demo_highcharts/master/Olympics2012CapitalLetter.csv"
  )
#> Rows: 10858 Columns: 8
#> ── Column specification ────────────────────────────────────
#> Delimiter: ","
#> chr (5): name, sport, nationality, sex, date_of_birth
#> dbl (3): age, height, weight
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
df = subset(df, select = -c(nationality, date_of_birth, name, age))

my_data <- df %>% filter((sport == "Gymnastics" &
                   sex == "male")  |
                  (sport == "Canoe" &
                     sex == "male") |
                  (sport == "Hockey" &
                     sex == "male") | (sport == "Modern Pentathlon" & sex == "male")
  )
my_data = subset(my_data, select = -c(sex))

my_data %>% head() %>% kable()
sport height weight
Canoe 2.02 115
Canoe 1.88 102
Canoe 1.88 100
Canoe 1.92 98
Canoe 1.88 98
Canoe 1.84 97
hcboxplot(
  x = my_data$height,
  var = my_data$sport,
  name = "Length",
  color = "#2980b9",
  outliers = TRUE
) %>%
  hc_chart(type = "column") %>% # type="bar" olursa yatay eksende gözükür
  # En üstte bulunan başlık
  hc_title(text = "Male height by descipline (Olympic 2012)") %>%
  # y eksenindeki değişiklikler için
  hc_yAxis(title = list(text = "Height in metre")) %>%
  # Grafiğin üstüne serpilme diyagramı eklemek için
  hc_add_series(
    data = my_data,
    type = "scatter",
    hcaes(x = "sport", y = "my_data$height", group = "sport")
  ) %>%
  # serpilme diyagramı ayarları için scatter = list(...)
  hc_plotOptions(scatter = list(
    color = "red",
    marker = list(
      radius = 2,
      symbol = "circle",
      lineWidth = 1
    )
  ))  %>%
  hc_plotOptions(scatter = list(jitter = list(x = .1, y = 0)))
#> Warning: 'hcboxplot' is deprecated.
#> Use 'data_to_boxplot' instead.
#> See help("Deprecated")
Created with Highcharts 9.3.1Height in metreMale height by descipline (Olympic 2012)CanoeGymnasticsHockeyModern Pentathlon1.41.51.61.71.81.922.1

3.1.7 Örnekler

data(favorite_bars)
favorite_bars %>% head() %>% kable()
bar percent
Mclaren’s 30
McGee’s 28
P & G 27
White Horse Tavern 12
King Cole Bar 3
data(favorite_pies)
favorite_pies %>% head() %>% kable()
pie percent
Strawberry Rhubarb 85
Pumpkin 64
Lemon Meringue 75
Blueberry 100
Key Lime 57
highchart() |> 
  # Data
  hc_add_series(
    favorite_pies, 
    "column",
    hcaes(
      x = pie,
      y = percent
      ),
    name = "Pie"
    ) |>
  hc_add_series(
    favorite_bars,
    "pie",
    hcaes(
      name = bar,
      y = percent
      ),
    name = "Bars"
    ) |>
  hc_plotOptions(
    series = list(
      showInLegend = FALSE,
      pointFormat = "{point.y}%",
      # her bir kategori için farklı renk
      colorByPoint = TRUE
      ),
    pie = list(
      # pie chart'ın konumu ve boyutu
      center = c('30%', '10%'),
      size = 120,
      dataLabels = list(enabled = FALSE)
      )
    ) |>
  # eksenler
  hc_yAxis(
    title = list(text = "percentage of tastiness"),
    labels = list(format = "{value}%"), 
    max = 100
  ) |> 
  hc_xAxis(
    categories = favorite_pies$pie
    ) |>
  # Titles, subtitle, caption and credits
  hc_title(
    text = "How I Met Your Mother: Pie Chart Bar Graph"
  ) |> 
  hc_subtitle(
    text = "This is a bar graph describing my favorite pies
    including a pie chart describing my favorite bars"
  ) |>
  hc_caption(
    text = "The values represented are in percentage of tastiness and awesomeness."
    ) |> 
  hc_credits(
    enabled = TRUE, text = "Source: HIMYM",
    href = "https://www.youtube.com/watch?v=f_J8QU1m0Ng",
    style = list(fontSize = "12px")
  ) |> 
  hc_size(
    height = 600
    )
Created with Highcharts 9.3.1percentage of tastinessHow I Met Your Mother: Pie Chart Bar GraphThis is a bar graph describing my favorite pies including a pie chart describing my favorite barsThe values represented are in percentage of tastiness and awesomeness.StrawberryRhubarbPumpkinLemon MeringueBlueberryKey Lime0%20%40%60%80%100%Source: HIMYM
df <- data.frame(
  stringsAsFactors = FALSE,
  name = c(
    "The Left",
    "Social Democratic Party",
    "Alliance 90/The Greens",
    "Free Democratic Party",
    "Christian Democratic Union",
    "Christian Social Union in Bavaria",
    "Alternative for Germany"
  ),
  count = c(69, 153, 67, 80, 200, 46, 94),
  col = c("#BE3075", "#EB001F", "#64A12D", "#FFED00",
          "#000000", "#008AC5", "#009EE0"
  ),
  abbrv = c("DIE LINKE", "SPD", "GRÜNE", "FDP", "CDU", "CSU", "AfD")
)

hchart(
  df,
  type="item",
  hcaes(
    name = name,
    y = count,
    label = abbrv,
    color = col
  ),
  name = "Representatives",
  # legendda gösterilmesi için
  showInLegend = TRUE,
  size = "100%",
  # pie chartın yerinin grafik alanına göre belirlenmesi (yatay, dikey)
  center = list("50%", "75%"),
  # pie chartarın başlama derecesi
  startAngle = -100,
  # pie chartın bitiş dercesi
  endAngle  = 100
) %>%
  hc_title(text = "Item chart with different layout") %>%
  hc_legend(labelFormat = '{name} <span style="opacity: 0.4">{y}</span>')
Created with Highcharts 9.3.1Item chart with different layoutThe LeftThe LeftSocial Democratic PartySocial Democratic PartyAlliance 90/The GreensAlliance 90/The GreensFree Democratic PartyFree Democratic PartyChristian Democratic UnionChristian Democratic UnionChristian Social Union in BavariaChristian Social Union i…Christian Social Union in BavariaChristian Social Union i…Alternative for GermanyAlternative for Ger…Alternative for GermanyAlternative for Ger…The Left 69Social Democratic Party 153Alliance 90/The Greens 67Free Democratic Party 80Christian Democratic Union 200Christian Social Union in Bavaria 46Alternative for Germany 94
library(forcats)
library(stringr)
library(purrr)
pkmn_min <- as.data.frame(pokemon) |>
  count(type_1, color = type_1_color) |>
  mutate(type_1 = fct_reorder(type_1, .x = n)) |>
  arrange(desc(type_1))

pkmn_ddn <- pokemon |>
  count(type_1, type_2, color = type_mix_color) |>
  arrange(type_1, desc(n)) |>
  mutate(type_2 = ifelse(is.na(type_2), str_c("only ", type_1), type_2)) |>
  group_nest(type_1) |>
  mutate(
    id = type_1,
    type = "column",
    # in the drilldown we'll give the mapping via creating the columns
    data = map(data, mutate, name = type_2, y  = n),
    data = map(data, list_parse)
  )

hchart(
  pkmn_min,
  type = "column",
  hcaes(x = type_1, y = n, color = color, drilldown = type_1),
  name = "Pokémons"
  ) |>
  hc_drilldown(
    activeAxisLabelStyle = list(textDecoration = "none"),
    allowPointDrilldown = TRUE,
    series = list_parse(pkmn_ddn)
  ) |>
  hc_yAxis(
    title = list(text = ""),
    endOnTick = FALSE,
    opposite = TRUE
    ) |>
  hc_xAxis(
    title = list(text = ""),
    endOnTick = FALSE,
    gridLineWidth = 0,
    tickWidth = 0
    ) |>
  hc_chart(
    style = list(fontFamily = "Gloria Hallelujah")
  )
Created with Highcharts 9.3.1waterwat…normalgrassbugpsychicfirerockelectricfightingdarkpoisongroundghostdragonsteelicefairyflying0100255075125
library(quantmod)
SPY <- getSymbols("SPY", from = Sys.Date() - lubridate::years(1), auto.assign = FALSE)
SPY <- adjustOHLC(SPY)

SPY.SMA.10 <- SMA(Cl(SPY), n = 5)
SPY.SMA.200 <- SMA(Cl(SPY), n = 100)
SPY.RSI.14 <- RSI(Cl(SPY))
SPY.RSI.SellLevel <- xts(rep(70, NROW(SPY)), index(SPY))
SPY.RSI.BuyLevel <- xts(rep(30, NROW(SPY)), index(SPY))


highchart(type = "stock") |> 
  hc_yAxis_multiples(create_yaxis(3, height = c(2, 1, 1), turnopposite = TRUE)) |> 
  hc_add_series(SPY, yAxis = 0, name = "SPY") |> 
  hc_add_series(SPY.SMA.10, yAxis = 0, name = "Fast MA") |> 
  hc_add_series(SPY.SMA.200, yAxis = 0, name = "Slow MA") |> 
  hc_add_series(SPY$SPY.Volume, color = "gray", yAxis = 1, name = "Volume", type = "column") |> 
  hc_add_series(SPY.RSI.14, yAxis = 2, name = "Osciallator", color = hex_to_rgba("green", 0.7)) |>
  hc_add_series(SPY.RSI.SellLevel, color = hex_to_rgba("red", 0.7), yAxis = 2, name = "Sell level") |> 
  hc_add_series(SPY.RSI.BuyLevel, color = hex_to_rgba("blue", 0.7), yAxis = 2, name = "Buy level") |> 
  hc_tooltip(valueDecimals = 2) |> 
  hc_size(height = 800)
Created with Highcharts 9.3.1Feb '22Apr '22Jun '22Aug '22Oct '22Dec '22Jan '22Apr '22Jul '22Oct '223253503754004254504755000100M200M300M0255075100ZoomView 1 month1mView 3 months3mView 6 months6mView year to dateYTDView 1 year1yView allAllDec 20, 2021Dec 19, 2022