-
Notifications
You must be signed in to change notification settings - Fork 3
/
diverging_bar_plt.Rd
82 lines (70 loc) · 2.61 KB
/
diverging_bar_plt.Rd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/diverging-bar-plt.R
\name{diverging_bar_plt}
\alias{diverging_bar_plt}
\title{Diverging Bar Chart}
\usage{
diverging_bar_plt(
.data,
.x_axis,
.y_axis,
.fill_col,
.plot_title = NULL,
.plot_subtitle = NULL,
.plot_caption = NULL,
.interactive = FALSE
)
}
\arguments{
\item{.data}{The data to pass to the function, must be a tibble/data.frame.}
\item{.x_axis}{The data that is passed to the x-axis.}
\item{.y_axis}{The data that is passed to the y-axis. This will also equal the
parameter \code{label}}
\item{.fill_col}{The column that will be used to fill the color of the bars.}
\item{.plot_title}{Default is NULL}
\item{.plot_subtitle}{Default is NULL}
\item{.plot_caption}{Default is NULL}
\item{.interactive}{Default is FALSE. TRUE returns a plotly plot}
}
\value{
A \code{plotly} plot or a \code{ggplot2} static plot
}
\description{
Diverging Bars is a bar chart that can handle both negative and positive
values. This can be implemented by a smart tweak with \code{geom_bar()}. But the
usage of \code{geom_bar()} can be quite confusing. That's because, it can be used to
make a bar chart as well as a histogram. Let me explain.
By default, \code{geom_bar()} has the stat set to count. That means, when you
provide just a continuous X variable (and no Y variable), it tries to make
a histogram out of the data.
In order to make a bar chart create bars instead of histogram,
you need to do two things. Set \code{stat = identity} and provide both \code{x} and \code{y}
inside \code{aes()} where, \code{x} is either character or factor and \code{y} is numeric.
In order to make sure you get diverging bars instead of just bars, make sure,
your categorical variable has 2 categories that changes values at a certain
threshold of the continuous variable. In below example, the mpg from mtcars
data set is normalized by computing the z score. Those vehicles with mpg
above zero are marked green and those below are marked red.
}
\details{
This function takes only a few arguments and returns a ggplot2 object.
}
\examples{
suppressPackageStartupMessages(library(ggplot2))
data("mtcars")
mtcars$car_name <- rownames(mtcars)
mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)
mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")
mtcars <- mtcars[order(mtcars$mpg_z), ] # sort
mtcars$car_name <- factor(mtcars$car_name, levels = mtcars$car_name)
diverging_bar_plt(
.data = mtcars
, .x_axis = car_name
, .y_axis = mpg_z
, .fill_col = mpg_type
, .interactive = FALSE
)
}
\author{
Steven P. Sanderson II, MPH
}