Skip to main content
v2026.11,986 entries · CC-BY 4.0

sns countplot: Seaborn Counts and Percentages

Count research records with Seaborn, audit missing statuses, and distinguish percentages of all plotted records from percentages within a site.

Written and maintained by CASRAI Editorial Board

Published

On this page

sns.countplot draws bars showing how many observations fall in each category. For research records, first define what one row represents, then check the plotted counts against a frequency table. The example below follows missing statuses through that check and distinguishes percentages of all plotted records from percentages within a site.

What it is used for in research

A count plot answers a categorical frequency question: how many records have each status, or how many observations belong to each recorded group. Seaborn’s categorical tutorial distinguishes this from barplot, which estimates a numeric variable within categories and takes the mean by default. Use the Seaborn barplot guide when your question concerns a measurement rather than the number of rows.

The counted unit deserves an explicit label. In a table with one row per specimen, a bar represents specimens; in a table with repeated visits, it represents visit records. Calling either chart “participants” would require a separate justification that the rows correspond to distinct participants. For the illustrative task here, the unit is simply a study record, and no inference about people or outcomes follows from the chart.

A useful research workflow keeps the input table, its inclusion rule and its chart together. Before using this example on your own data, write down whether you want all records, records with an assigned status, or records with both status and site recorded. Those are different questions. The plotting function should receive the table that answers the chosen question.

Install or access

The official Seaborn installation guide gives pip install seaborn. If multiple Python installations cause an import mismatch, it also documents python -m pip install seaborn, which invokes pip through that interpreter. Run installation commands in a terminal associated with the environment used for your analysis.

pip install seaborn

For a conda environment, the documented commands are conda install seaborn or conda install seaborn -c conda-forge. Choose the installation route appropriate to your existing environment. Seaborn’s mandatory dependencies include pandas, NumPy and Matplotlib; the example uses pandas for the audit and Matplotlib for displaying the figure.

Import the libraries in the analysis session before running the task. The official documentation uses the aliases below. Printing the versions alongside the analysis makes a later error report more specific, especially when an older notebook encounters newer function arguments.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

print("Seaborn:", sns.__version__)
print("pandas:", pd.__version__)

Step-by-step task: seaborn countplot

This is an illustrative composite made from synthetic research-record statuses, not observations from a real study. It contains two sites and one missing status so that the selection rule is visible. Run the blocks in order in the same session.

  1. Create the demonstration records. Each position in the two lists describes one record. Site A has six records; site B has seven, including the record with no status. The missing value is deliberate: it gives the audit something concrete to detect.
df = pd.DataFrame({
    "status": [
        "Complete", "Complete", "Complete", "Complete",
        "Pending", "Excluded",
        "Complete", "Pending", "Pending", "Pending",
        "Excluded", "Excluded", None
    ],
    "site": ["A"] * 6 + ["B"] * 7
})
print(df["status"].value_counts(dropna=False))

The audit has five Complete records, four Pending records, three Excluded records and one missing status. pandas documents that value_counts() excludes missing values by default; dropna=False makes them visible. Without that option, the first audit would hide the distinction between the thirteen input records and the twelve records with an assigned status.

  1. Define the table to plot. For this task, retain only records with both status and site recorded. The subset argument limits the missing-value check to those columns, as specified in pandas’ DataFrame.dropna documentation.
plot_df = df.dropna(subset=["status", "site"])
order = ["Complete", "Pending", "Excluded"]
print("Input records:", len(df))
print("Plotted records:", len(plot_df))
print(plot_df["status"].value_counts())

The resulting table has twelve records. This exclusion is part of the illustrative task, not a general rule for handling missing research data. If your analytical question requires showing an unassigned category, decide how that category is represented before plotting. Preserve the initial audit so a reader can see that one record was set aside.

  1. Draw the count plot. Pass the record table as data and the categorical column as x. The explicit order makes the status sequence a deliberate choice rather than a consequence of the order in which records happen to appear.
ax = sns.countplot(
    data=plot_df,
    x="status",
    order=order,
    color="steelblue"
)
ax.set(xlabel="Record status", ylabel="Number of study records")
plt.show()

The expected bar heights are 5, 4 and 3, in that order. Check those numbers against the printed table before changing the presentation. The total is twelve because this chart uses plot_df. Its title, caption and accompanying table should describe that same set of records.

  1. Add the second categorical variable. Supply site as hue to separate site A and site B within each status. Keep the same record selection and status order so the grouped chart answers a refinement of the original question.
ax = sns.countplot(
    data=plot_df,
    x="status",
    hue="site",
    order=order,
    hue_order=["A", "B"],
    dodge=True
)
ax.set(xlabel="Record status", ylabel="Number of study records")
plt.show()

For this synthetic input, site A contributes 4 Complete, 1 Pending and 1 Excluded record; site B contributes 1, 3 and 2. Summing the two site bars within each status recovers the ungrouped chart. Summing all six bars recovers the twelve retained records. These two checks catch a change in filtering or an unexpected category assignment without relying on the picture alone.

Output and how to read it

The default count chart reports frequency. Read the categorical labels, then the count axis, then the legend if a grouping variable is present. Seaborn’s tutorial treats categorical positions as equally spaced by default, even when category labels look numeric. Do not interpret a gap between category positions as a measured interval.

Whole-plot percentages and site percentages

The countplot API documents stat='percent' as normalization across the plot: bar heights sum to 100. It does not make every site group sum to 100. This argument was added in Seaborn 0.13.0, so check the installed version when adapting older code.

ax = sns.countplot(
    data=plot_df,
    x="status",
    hue="site",
    order=order,
    hue_order=["A", "B"],
    stat="percent",
    dodge=True
)
ax.set(xlabel="Record status", ylabel="Percent of plotted records")
plt.show()

In this example, the Complete bar for site A is 4 / 12 × 100 = 33.33%, rounded to two decimals. Its share within site A would instead be 4 / 6 × 100 = 66.67%. Both calculations are valid descriptions of this synthetic table, but they answer different questions. A label that only says “percentage” leaves the denominator unclear.

For a separate within-site audit, take one site’s status series and normalize its frequencies with pandas. Its documented normalize=True option returns relative frequencies. Here, after restricting the data to site A, the three proportions are approximately 0.6667, 0.1667 and 0.1667. Multiplying each by 100 converts them to percentages.

site_a = plot_df.loc[plot_df["site"] == "A", "status"]
print(site_a.value_counts(normalize=True))

Keep that calculation distinct from the whole-plot chart. In a report, a caption could state: “Illustrative study-record statuses; twelve records with status and site recorded; bar heights show percentages of those twelve records.” The wording makes the exclusion and denominator available to someone reading the figure without the notebook.

Troubleshooting

Counts disagree with the expected totals

Compare the table passed to the plotting function with the table passed to the frequency calculation. In this task, auditing df with missing values included gives thirteen records, while plotting plot_df gives twelve. That difference follows from the explicit selection, rather than a plotting error.

Also check whether the input contains observations or an already aggregated table. Three summary rows containing counts of 5, 4 and 3 are not twelve observation rows. For supplied bar heights, use a plotting method that accepts heights directly. A Seaborn histogram serves a different task when a numeric measurement needs binning.

Unrelated missing columns remove records

pandas’ dropna() checks for any missing value across columns by default. Restricting subset to the variables needed for this plot prevents an unrelated incomplete field from silently changing this example’s selection rule. Examine the retained row count after filtering and explain the chosen rule in the analysis record.

An older snippet fails

Use named arguments for the category: sns.countplot(data=plot_df, x='status'). In the documented signature, arguments following data are keyword-only. For a failure involving stat, compare the installed Seaborn version with the argument’s documented introduction in 0.13.0.

For an import failure, follow the official installation guide’s advice to identify which library failed from the traceback. Its environment-mismatch guidance explains why installing a package in one interpreter does not ensure that another interpreter can import it. A small synthetic example and the package versions make a useful error report without sharing research records.

Labels or colours obscure the comparison

For long category names, move the category to y to obtain a horizontal count plot. Keep the order explicit. For grouped colours, the documented palette parameter maps levels of hue; the Seaborn colour-scale guide explains the distinction between categorical palettes and continuous colormaps.

For this example, run sns.countplot(data=plot_df, y='status', order=order) to inspect the horizontal layout. The category names move to the vertical axis, and the horizontal axis carries the counts. The expected lengths remain 5, 4 and 3; changing orientation should not change which records the example counts.

The data table below separates the documented operations for auditing missing values, selecting rows and normalizing output. Use it to identify which stage changed a total before adjusting the appearance of the chart.

Free alternatives

The alternatives below use pandas, Matplotlib or Seaborn functions in the same Python workflow. Choose based on whether you need to count raw records, display counts already calculated, or divide a figure into panels. The input and return types come from their respective official references.

Method Input and role Result to work with
pandas Series.plot.bar Plot a frequency series already produced by value_counts; aggregation remains a separate visible step. A Matplotlib Axes for an ordinary single plot.
Matplotlib Axes.bar Supply categorical labels and numeric heights directly. A BarContainer containing the bars.
Seaborn catplot with kind=’count’ Count raw observations and use row or col to split categories into panels. A FacetGrid rather than a single Axes.

For example, plot_df['status'].value_counts().plot.bar() turns the audited frequency series into a chart. With Matplotlib, the equivalent separation is counts = plot_df['status'].value_counts(), followed by ax.bar(counts.index, counts.values) on an existing Axes. Matplotlib documents that repeated categorical labels occupy the same position, so passing repeated raw labels there would overlap bars rather than count them.

For site panels, use sns.catplot(data=plot_df, x='status', col='site', order=order, kind='count'). Its figure-level interface returns a grid; use the grid’s set_axis_labels method for labels. Regardless of presentation, keep the twelve-record selection and the 5/4/3 frequency audit fixed while comparing the results.

Sources

Data: Countplot audit, selection and normalization settings

Original compilation of documented pandas and Seaborn settings that distinguish a missing-value audit, row selection and normalization of displayed counts. Compiled from the official API references; no synthetic study counts are included.

Countplot audit, selection and normalization settings
OperationDocumented settingEffectOfficial reference
Audit unassigned categoriesSeries.value_counts(dropna=False)Includes missing values in the frequency output.https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html
Select rows for named variablesDataFrame.dropna(subset=[column labels])Restricts the missing-value check to the named columns; default row removal applies if any checked value is missing.https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html
Display absolute frequenciesseaborn.countplot(stat='count')Shows counts of observations in categorical bins.https://seaborn.pydata.org/generated/seaborn.countplot.html
Display whole-plot sharesseaborn.countplot(stat='percent')Normalizes bar heights to sum to 100 across the plot.https://seaborn.pydata.org/generated/seaborn.countplot.html
Audit relative frequenciesSeries.value_counts(normalize=True)Returns relative frequencies rather than absolute counts; missing values are excluded by default.https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about sns countplot: Seaborn Counts and Percentages

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →