visualizeR/vignettes/bar_charts.Rmd
2025-02-09 17:19:54 +01:00

57 lines
1.5 KiB
Text

---
title: "Bar charts"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Bar charts}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
Let's start by importing some data and running some data wrangling:
```{r data-import}
library(rio)
library(data.table)
dat <- import("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/11_SevCatOneNumNestedOneObsPerGroup.csv", data.table = TRUE)
setDT(dat)
# in all character columns, tranform empty string to NA
vars_chr <- colnames(dat)[sapply(dat, is.character)]
dat[, (vars_chr) := lapply(.SD, function(x) fifelse(x == "", NA_character_, x)), .SDcols = vars_chr]
# in value, if -1 replace with NA
dat[, value := fifelse(value == -1, NA_real_, value)]
# remove lines where value is NA (in place)
dat <- dat[!is.na(value), ]
# kepp only top 20 values and divide data to get million units
df <- dat[
!is.na(value), ][
order(value, decreasing = TRUE), ][
1:20, ][
, value := value/1000000, ][
, key := ifelse(key == "Democratic Republic of the Congo", "DRC", key)]
```
Now, let's see the defaults for a horizontal bar diagram without any grouping and ordering values from highest to smallest:
```{r hbar}
library(visualizeR)
hbar(
df,
x = "key",
y = "value",
facet = "region",
order = "y",
title = "Top 20 countries by population (in Million)"
)
```
Moving on to a vertical bar chart, with country facets and groups