pydataviz reference

What this page's Python has, and the names you will use most, each with the arguments it takes. Every line here is plain Python: it runs the same in IDLE on a computer with these libraries installed. Each call lists the arguments used most; help(name) prints all of them.

What is here

Python 3.14.2, running in the browser on Pyodide 314.0.6, with these libraries:

LibraryImport it withFor
pandas 3.0.2import pandas as pdTables: read them, choose from them, group and summarize them.
matplotlib 3.10.8import matplotlib.pyplot as pltCharts as pictures, with matplotlib's window tools.
plotly 7.1.0import plotly.express as pxCharts you can hover over, zoom, and step through with a slider.
numpy 2.4.6import numpy as npArrays of numbers. pandas and matplotlib are built on it.
pillow 12.2.0from PIL import ImagePictures: open, change and save them.

import plotly.graph_objects as go is plotly too. These come along because the libraries above use them, and can be imported too: contourpy 1.3.3, cycler 0.12.1, fonttools 4.62.1, kiwisolver 1.5.0, narwhals 2.18.1, packaging 26.1, pyparsing 3.3.2, python-dateutil 2.9.0.post0, pytz 2026.1.post1, six 1.17.0.

The whole standard library is here except idlelib, tkinter, turtle, turtledemo (they open windows of their own); curses, readline (they need a terminal); ensurepip, venv (nothing is installed here); dbm, pydoc_data (not built for a browser); grp, msvcrt, nt, pwd, resource, syslog, winreg, winsound (they exist only on Windows, or only on Mac and Linux).

How it differs from IDLE

pandas

import pandas as pd. A table is a DataFrame, written df here; one column of it is a Series, written s (for example s = df["score"]).

Reading a file

pd.read_csv(filepath_or_buffer, sep=',', header='infer', usecols=None, dtype=None, na_values=None, parse_dates=None, encoding=None)

Read a CSV (or any delimited) file into a DataFrame. sep="\t" reads a tab-separated file.

pd.read_json(path_or_buf, orient=None, dtype=None)

Read a JSON file into a DataFrame.

pd.DataFrame(data=None, columns=None)

Make a DataFrame from a dictionary of columns or a list of rows.

Looking at a table

df.head(n=5)

The first rows.

df.tail(n=5)

The last rows.

df.sample(n=None, random_state=None)

Rows picked at random.

df.info()

Prints each column's name, type and count of filled cells.

df.describe(include=None)

Count, mean, spread and quartiles of each number column.

df.shape

(rows, columns), as a tuple.

df.columns

The column names.

df.dtypes

The type pandas gave each column.

df.index

The row labels.

Choosing rows and columns

df["col"]

One column, as a Series. A name with a space or a dot in it only works this way, never as df.col.

df[["a", "b"]]

Several columns, as a DataFrame.

df[df["col"] > 5]

The rows where a condition is true. Join conditions with & (and) or | (or), each in parentheses.

df.loc[rows, "col"]

Rows and columns by label or condition.

df.iloc[i, j]

Rows and columns by position, counting from 0.

df["new"] = ...

Add a column, or replace one.

df.query(expr)

The rows where an expression, written as a string, is true.

df.isin(values)

True where a cell is one of the values given.

df.nlargest(n, columns)

The n rows with the largest values in a column.

df.nsmallest(n, columns)

The n rows with the smallest values in a column.

Cleaning

df.dropna(axis=0, how='any', subset=None)

Leave out rows (or columns) with a missing value.

df.fillna(value)

Fill missing values.

df.isna()

True where a value is missing.

df.drop(labels=None, columns=None)

Leave out rows or columns by name.

df.rename(columns=None)

Rename columns, from a dictionary of old name to new.

df.astype(dtype)

Change the type of a column, or of every column.

df.drop_duplicates(subset=None, keep='first')

Leave out repeated rows.

pd.to_datetime(arg, format=None, errors='raise')

Turn text into dates.

pd.to_numeric(arg, errors='raise')

Turn text into numbers; errors="coerce" makes the ones that are not numbers missing.

Arranging and grouping

df.sort_values(by, ascending=True)

Sort the rows by one or more columns.

df.set_index(keys)

Use a column as the row labels.

df.reset_index(drop=False)

Turn the row labels back into a column.

df.groupby(by=None)

Split the rows into groups by the values in a column. Follow it with a column and a summary, or with .agg.

df.agg(func=None)

One or more summaries, by name: "mean", "sum", "count"...

df.pivot_table(values=None, index=None, columns=None, aggfunc='mean')

A summary table, with one column's values down the side and another's across.

pd.crosstab(index, columns)

How often each pair of values occurs together.

df.merge(right, how='inner', on=None)

Join two tables on a column they share.

pd.concat(objs, axis=0)

Stack tables, one under another (or side by side).

df.melt(id_vars=None, value_vars=None)

Turn wide columns into long rows.

pd.cut(x, bins, labels=None)

Sort numbers into ranges.

Numbers from a table

df.mean(numeric_only=False)

The mean of each column.

df.median(numeric_only=False)

The median of each column.

df.sum(numeric_only=False)

The total of each column.

df.count()

The filled cells in each column.

df.min(numeric_only=False)

The smallest value in each column.

df.max(numeric_only=False)

The largest value in each column.

df.std(numeric_only=False)

The standard deviation of each column.

df.corr(method='pearson', numeric_only=False)

How closely each pair of columns rises and falls together.

df.round(decimals=0)

Round every number.

df.value_counts(subset=None)

How often each row occurs.

df.nunique()

How many different values each column has.

One column: a Series

s.mean()

The mean.

s.median()

The median.

s.mode()

The most common value (or values).

s.sum()

The total.

s.min()

The smallest value.

s.max()

The largest value.

s.std()

The standard deviation.

s.quantile(q=0.5)

The value a fraction of the way up.

s.idxmax()

The row label of the largest value.

s.idxmin()

The row label of the smallest value.

s.value_counts(normalize=False, sort=True)

How often each value occurs.

s.unique()

Each different value, once.

s.nunique()

How many different values there are.

s.isna()

True where a value is missing.

s.between(left, right)

True where a value is in a range.

s.apply(func)

Call a function on every value.

s.map(func=None)

Replace each value, by a dictionary or a function.

s.cumsum()

A running total.

s.diff(periods=1)

Each value minus the one before.

s.rolling(window)

A moving window; follow it with a summary such as .mean().

s.round(decimals=0)

Round every number.

s.tolist()

The values as a plain list.

s.str

Text methods on every value: s.str.lower(), s.str.contains(...)...

s.dt

Date parts of every value: s.dt.year, s.dt.month...

Writing and drawing

df.to_csv(path_or_buf=None, index=True)

Write the table to a CSV file in your folder.

df.plot(x=None, y=None, kind='line', title=None)

A matplotlib chart of the table; plt.show() shows it.

df.iterrows()

Each row in turn, as (label, Series), for a loop.

matplotlib.pyplot

import matplotlib.pyplot as plt. Each call draws on the current figure; plt.show() shows it in the chart pane.

Kinds of chart

plt.plot(y)

plt.plot(x, y)

plt.plot(x, y, fmt)

Lines (and markers) through points. fmt is a short string such as "o-" or "r--".

Line keywords: color=, linestyle=, linewidth=, marker=, markersize=, alpha=, label=

plt.scatter(x, y, s=None, c=None, marker=None, alpha=None)

A dot for each point. s is the size, c the color.

Other keywords: label=, edgecolor=

plt.bar(x, height, width=0.8)

Vertical bars.

Bar keywords: color=, edgecolor=, label=

plt.barh(y, width, height=0.8)

Horizontal bars.

Bar keywords: color=, edgecolor=, label=

plt.hist(x, bins=None, range=None, density=False, histtype='bar', color=None, label=None)

A histogram: how many values fall in each range.

Bar keywords: edgecolor=, alpha=

plt.boxplot(x, vert=None, tick_labels=None)

A box plot of each list of values.

plt.pie(x, labels=None, colors=None, autopct=None)

A pie chart.

plt.errorbar(x, y, yerr=None, xerr=None, fmt='', capsize=None)

Points with error bars.

plt.fill_between(x, y1, y2=0)

Shade the area between two lines.

Fill keywords: color=, alpha=, label=

plt.axhline(y=0)

A horizontal line across the axes.

Line keywords: color=, linestyle=, linewidth=, label=

plt.axvline(x=0)

A vertical line across the axes.

Line keywords: color=, linestyle=, linewidth=, label=

Words and axes

plt.title(label)

A title above the axes.

plt.xlabel(xlabel)

Label the x axis.

plt.ylabel(ylabel)

Label the y axis.

plt.legend()

A key to everything drawn with a label.

Keywords: loc=, title=

plt.grid(visible=None, axis='both')

Grid lines.

plt.xlim(left, right)

The x axis's range.

plt.ylim(bottom, top)

The y axis's range.

plt.xscale(value)

"log" for a logarithmic x axis.

plt.yscale(value)

"log" for a logarithmic y axis.

plt.xticks(ticks=None, labels=None)

Where the x axis's marks go, and what they say.

Label keywords: rotation=, fontsize=

plt.yticks(ticks=None, labels=None)

Where the y axis's marks go, and what they say.

plt.text(x, y, s)

Words at a point.

plt.annotate(text, xy, xytext=None, arrowprops=None)

Words pointing at a point, with an arrow.

Figures

plt.figure(figsize=None)

Start a new figure. figsize is (width, height) in inches.

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False)

A figure and its axes, in a grid: fig, ax = plt.subplots().

Figure keywords: figsize=

plt.tight_layout()

Make room so labels do not overlap.

plt.savefig(fname)

Save the figure as a file in your folder.

Keywords: dpi=, bbox_inches=, transparent=

plt.show()

Show the figure in the chart pane.

plt.close(fig=None)

Throw a figure away.

Axes, after fig, ax = plt.subplots()

ax.plot(...), ax.scatter(...), ax.bar(...), ax.hist(...)

The same charts as above, drawn on one particular set of axes.

ax.set_title(label)

A title above these axes.

ax.set_xlabel(xlabel)

Label the x axis.

ax.set_ylabel(ylabel)

Label the y axis.

ax.set_xlim(left=None, right=None)

The x axis's range.

ax.set_ylim(bottom=None, top=None)

The y axis's range.

ax.legend()

A key to these axes.

ax.grid(visible=None)

Grid lines.

ax.twinx()

A second y axis on the right, sharing the x axis.

fig.suptitle(t)

A title over the whole figure.

plotly.express

import plotly.express as px. Each function makes a figure from a DataFrame and the names of its columns; fig.show() shows it in the chart pane with plotly's own controls.

Charts

px.scatter(data_frame=None, x=None, y=None, color=None, title=None, size=None, hover_name=None, trendline=None)

A dot for each row.

px.line(data_frame=None, x=None, y=None, color=None, title=None, markers=False)

Lines through the rows, in order.

px.bar(data_frame=None, x=None, y=None, color=None, title=None, barmode='relative', orientation=None)

Bars.

px.histogram(data_frame=None, x=None, color=None, nbins=None, histfunc=None, title=None)

How many rows fall in each range.

px.box(data_frame=None, x=None, y=None, color=None, title=None, points=None)

Box plots.

px.violin(data_frame=None, x=None, y=None, color=None, title=None, box=False)

Violin plots.

px.strip(data_frame=None, x=None, y=None, color=None, title=None)

Every value as a dot, in a strip.

px.pie(data_frame=None, names=None, values=None, title=None)

A pie chart.

px.area(data_frame=None, x=None, y=None, color=None, title=None)

Stacked areas.

px.scatter_matrix(data_frame=None, dimensions=None, color=None)

A scatter plot of every pair of columns.

px.density_heatmap(data_frame=None, x=None, y=None, z=None, nbinsx=None, nbinsy=None)

A grid colored by how many rows fall in each square.

px.imshow(img, text_auto=False, color_continuous_scale=None)

A grid of numbers as colors.

px.sunburst(data_frame=None, path=None, values=None)

Rings of categories inside categories.

px.treemap(data_frame=None, path=None, values=None)

Rectangles of categories inside categories.

Keywords most of them take

labels=None, hover_data=None, facet_col=None, facet_row=None, animation_frame=None, log_x=False, log_y=False, range_x=None, range_y=None, width=None, height=None

Taken by px.scatter, px.line, px.bar, px.histogram and px.box. labels renames columns on the chart; facet_col makes one small chart per value; animation_frame adds a slider that steps through a column's values.

Sample tables, built in

px.data.gapminder()

Countries' life expectancy, population and income, every five years.

px.data.iris()

Measurements of 150 iris flowers.

px.data.tips()

Restaurant bills and tips.

px.data.wind()

Wind strength by direction.

px.data.stocks()

Six companies' stock prices over two years.

px.data.medals_long()

Medal counts by country.

plotly.graph_objects

import plotly.graph_objects as go. Build a figure a piece at a time, or change one that px made: fig is a figure either way.

A figure and what goes in it

go.Figure(data=None, layout=None, frames=None)

A figure. frames are the steps of an animation or a slider.

go.Scatter(x=None, y=None, mode=None, name=None, marker=None, line=None)

Points or lines. mode is "markers", "lines" or "lines+markers".

go.Bar(x=None, y=None, name=None, orientation=None)

Bars.

go.Histogram(x=None, nbinsx=None, name=None)

A histogram.

go.Box(y=None, name=None)

A box plot.

go.Pie(labels=None, values=None)

A pie chart.

go.Heatmap(z=None, x=None, y=None, colorscale=None)

A grid of numbers as colors.

go.Frame(data=None, name=None, layout=None)

One step of an animation; a slider in the layout moves between them by name.

Changing a figure

fig.show()

Show it in the chart pane.

Keywords: config=, auto_play=

fig.add_trace(trace, row=None, col=None)

Add a go.Scatter, go.Bar... to the figure.

fig.update_layout()

Change the figure's titles, size, legend, sliders and buttons.

Layout keywords: title=, xaxis_title=, yaxis_title=, width=, height=, showlegend=, legend_title=, template=, sliders=, updatemenus=

fig.update_traces()

Change every trace at once.

Trace keywords: marker_size=, marker_color=, line_width=, line_dash=, opacity=, mode=

fig.update_xaxes()

Change the x axis.

Axis keywords: title=, range=, type=, showgrid=, tickangle=

fig.update_yaxes()

Change the y axis.

Axis keywords: title=, range=, type=, showgrid=

fig.add_hline(y)

A horizontal line across the plot.

Line keywords: line_dash=, line_color=

fig.add_vline(x)

A vertical line across the plot.

Line keywords: line_dash=, line_color=

fig.add_annotation(x=None, y=None, text=None, showarrow=None)

Words at a point, with or without an arrow.

fig.write_html(file)

Save the figure as a web page in your folder, controls and all.

make_subplots(rows=1, cols=1, subplot_titles=None)

A figure with a grid of plots (from plotly.subplots import make_subplots); add_trace takes row and col.

The standard library, and the built-in functions

Plain Python, for reading a file with a loop before pandas does it for you.

Built in

open(file, mode='r', encoding=None, newline=None)

Open a file in your folder. Use it in a with block.

sorted(iterable, key=None, reverse=False)

A sorted list.

sum(iterable)

The total.

min(iterable, key=None)

The smallest.

max(iterable, key=None)

The largest.

len(obj)

How many.

round(number, ndigits=None)

Round a number.

zip(*iterables)

Pairs from two lists.

enumerate(iterable, start=0)

Each item with its position.

help(thing)

Print everything about a name, every argument included.

csv

csv.reader(file, delimiter=',')

Each row as a list of strings.

csv.DictReader(f, fieldnames=None, delimiter=',')

Each row as a dictionary, keyed by the header.

csv.writer(file)

Write rows of a list each.

csv.DictWriter(f, fieldnames)

Write rows of a dictionary each.

statistics

statistics.mean(data)

The mean.

statistics.median(data)

The median.

statistics.mode(data)

The most common value.

statistics.stdev(data)

The standard deviation of a sample.

statistics.quantiles(data, n=4)

Cut points that split the data evenly.

statistics.correlation(x, y)

How closely two lists rise and fall together, from -1 to 1.

statistics.linear_regression(x, y)

The slope and intercept of the best straight line.

math, json, collections, datetime, random

math.sqrt(x)

A square root.

math.isclose(a, b, rel_tol=1e-09)

Are two floats close enough to equal?

json.load(fp)

Read a JSON file into lists and dictionaries.

json.dump(obj, fp, indent=None)

Write lists and dictionaries as JSON.

collections.Counter(iterable)

Count things; .most_common(n) gives the top n.

datetime.strptime(date_string, format)

Read a date and time from text.

date.fromisoformat(date_string)

Read a date written 2024-06-15.

random.seed(a=None)

Make the random numbers the same each run.

random.choice(seq)

One item at random.

random.sample(population, k)

Several different items at random.