bar_plot | R Documentation |
Plot a bar plot using ggplot2.
bar_plot( df, x_var, fill_var = NULL, y_var = NULL, style = c("stack", "fill", "dodge")[1], group_by_x_var = TRUE, y_percent = TRUE, percent_accuracy = 1, y_lim = NULL, y_breaks = 2000, x_breaks = NULL, y_breaks_end = 1e+05, title = NULL, subtitle = NULL, y_lab = NULL, x_lab = NULL, fill_colors = NULL, legend_labels = ggplot2::waiver(), label_breaks = ggplot2::waiver(), legend_row = NULL, legend_col = NULL, expand = FALSE, flip = FALSE, ... )
df |
Data frame. |
x_var |
Variable for x axis, use string name.
Recommended that |
fill_var |
Variable for the different colors in bars,
use string name.
Use |
y_var |
Variable for y axis, if |
style |
3 different styles of bar plots,
"stack", "fill", or "dodge".
fill requires |
group_by_x_var |
Only relevant for style dodge. Boolean indicating
if percentages should be for |
y_percent |
If |
percent_accuracy |
Set accuracy for |
y_lim |
Limit on y axis. |
x_breaks, y_breaks |
Length between each break on x/y axis. |
y_breaks_end |
Break end, default for 100,000. Works for all count values below that. |
title |
Plot title, |
subtitle |
Small text under title, |
y_lab |
Y-axis label, use |
x_lab |
X-axis label, use |
fill_colors |
Color of the different categories in |
legend_labels |
Label for each legend key. |
label_breaks |
Order of the legend keys. |
legend_row |
How many rows for the legends. |
legend_col |
How many columns for the legends. |
expand |
If |
flip |
If |
... |
arguments passed to |
ggplot object containing bar plot.
# Example data df <- ggplot2::diamonds # Style stack bar_plot(df, 'color', 'cut', y_breaks = 2) bar_plot(df, 'color', 'cut', y_percent = FALSE, y_breaks = 2000) # Style stack with y variable included df2 <- dplyr::group_by(df, color, cut) %>% dplyr::summarise(y = dplyr::n(), .groups = "drop_last") bar_plot(df2, 'color', 'cut', y_var = 'y', y_breaks = 2) # Style fill bar_plot(df, 'color', 'cut', y_breaks = 10, style = 'fill') # Style dodge grouped by x_var (color in this case) bar_plot(df, 'color', 'cut', style = 'dodge', y_breaks = 10) bar_plot(df, 'color', 'cut', style = 'dodge', y_percent = FALSE, y_breaks = 2000) # Style dodge grouped by fill_var (cut in this case) bar_plot(df, 'color', 'cut', style = 'dodge', group_by_x_var = FALSE, y_breaks = 10) # Since bar_plot() returns ggplot object, it is possible to add more features # Here we zoom the plot using coord_cartesian(): df3 <- dplyr::filter(df, clarity %in% c('SI1', 'SI2', 'VS2')) bar_plot(df3, 'clarity', style = 'dodge', y_percent = FALSE, y_breaks = 2000) + ggplot2::coord_cartesian(ylim = c(8000, 14000))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.