ANALYSIS TOOL BOX

Visualizations

PlotSingleVariableCountPlot

Generate a formatted horizontal bar chart showing frequency counts for a single categorical variable.

visualizationchartsplottinggraphs

Introduction

Before modeling or reporting on a categorical variable, it helps to see the shape of it directly: which levels dominate, which are vanishingly rare, and whether the distribution is balanced enough to trust downstream analysis. PlotSingleVariableCountPlot renders a sorted horizontal bar chart of category frequencies, with optional highlighting of the top N categories and a threshold line for flagging rare ones — a fast, honest first look at any categorical column.

Teaching Note

Single-variable count plots are essential for:

  • Epidemiology: Visualizing the distribution of confirmed disease sub-types within a cohort.
  • Healthcare: Analyzing the frequency of specific primary diagnoses in an outpatient clinic.
  • Intelligence Analysis: Monitoring the count of reported security incidents by geographic sector.
  • Data Science: Inspecting class balance or verifying the frequency of categorical feature levels.
  • Public Health: Tracking the most common symptoms reported during a regional health survey.
  • Operations: Visualizing the distribution of equipment failure modes across a facility.
  • Marketing: Identifying the most frequent sources of incoming customer leads.
  • Finance: Analyzing the volume of different transaction types processed in a cycle.

Parameters

ParameterTypeDefaultDescription
dataframerequiredpd.DataFrameThe pandas DataFrame containing the categorical data to analyze.
categorical_column_namerequiredstrThe name of the column containing the categorical levels to be counted.
fill_colorstr'#8eb3de'The hex color code for the bars when no highlighting or palette is applied. Defaults to '#8eb3de'.
color_palettestrNoneThe name of a seaborn color palette to apply to the categories. If provided, this overrides fill_color. Defaults to None.
top_n_to_highlightintNoneThe number of top categories (highest counts) to color with highlight_color. All other bars will be greyed out. Defaults to None.
highlight_colorstr'#b0170c'The hex color code used for bars that meet the top_n_to_highlight criteria. Defaults to '#b0170c'.
fill_transparencyfloat0.8The transparency level (alpha) of the bar fills (0 to 1). Defaults to 0.8.
add_rare_category_lineboolFalseWhether to overlay a vertical dashed line indicating the threshold for 'rare' categories. Defaults to False.
rare_category_line_colorstr'#b5b3b3'The hex color code for the rare category threshold line. Defaults to '#b5b3b3'.
rare_category_thresholdfloat0.05The percentage threshold (e.g., 0.05 for 5%) used to define 'rare' categories. Defaults to 0.05.
figure_sizetuple(8, 6)Dimensions of the output figure as a (width, height) tuple in inches. Defaults to (8, 6).
data_label_fontsizeint10The font size for the numeric text labels next to the bars. Defaults to 10.
data_label_paddingfloatNoneThe horizontal offset for the numeric labels. If None, it is calculated automatically. Defaults to None.
title_for_plotstrNoneThe primary title text displayed at the top of the chart. Defaults to None.
subtitle_for_plotstrNoneDescriptive subtitle text displayed below the main title. Defaults to None.
caption_for_plotstrNoneExplanatory text or notes at the bottom of the plot. Defaults to None.
data_source_for_plotstrNoneText identifying the data source, appended to the caption. Defaults to None.
title_y_indentfloat1.15Vertical offset for the title position relative to the axes. Defaults to 1.15.
subtitle_y_indentfloat1.1Vertical offset for the subtitle position relative to the axes. Defaults to 1.1.
caption_y_indentfloat-0.15Vertical offset for the caption position relative to the axes. Defaults to -0.15.
filepath_to_save_plotstrNoneThe local path (ending in .png or .jpg) where the plot should be exported. If None, the file is not saved. Defaults to None.

Returns

None — the function displays the count plot using matplotlib and optionally saves it to disk.

Example

python
from analysistoolbox.visualizations import PlotSingleVariableCountPlot
import pandas as pd

# Epidemiology: distribution of viral sub-types
epi_df = pd.DataFrame({
    'Subtype': ['Type A', 'Type A', 'Type B', 'Type A', 'Type C', 'Type B', 'Type A', 'Type D']
})
PlotSingleVariableCountPlot(
    epi_df, 'Subtype',
    top_n_to_highlight=1,
    title_for_plot="Viral Variant Prevalence",
    subtitle_for_plot="Frequency of detected subtypes in Q1 laboratory samples"
)