plot-utils

A Python library for elegant data visualization


Keywords
data-visualization, python, visualization
License
GPL-3.0
Install
pip install plot-utils==0.6.12

Documentation

Python plotting utilities: plot_utils

PyPI Documentation Status Downloads Downloads Downloads

This is a Python module that contains some useful data visualization tools.

Table of contents:

1. Installation

In the terminal, run the following command:

pip install plot-utils
Note:

If you run into the following issue on Mac OS X (or macOS) when importing plot_utils:

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.

please follow this solution to fix the issue: https://stackoverflow.com/a/21789908/8892243

2. API documentations

All API documentations are on: https://python-plot-utils.readthedocs.io/en/stable/index.html.

3. Current functionalities

Current functionalities include (for full list, use print(plot_utils.__doc__)):

3.1. Visualizing one column of data

  • Pie chart: proportions of distinct values in an array, more convenient than matplotlib's pie() function [doc], [example]
  • Discrete histogram: counts of distinct values in an array [doc], [example]

3.2. Visualizing two columns of data ([example])

  • "Bin-and-mean" plot: for two continuous variables [doc]
  • Category mean: for a categorical variable and a continuous variable [doc]
  • Positive rate: for a categorical variable and a binary categorical variable [doc]
  • Contingency table: for two categorical variables [doc]

3.3. Visualizing multiple columns of data

  • 3D histograms: distributions of multiple variables [doc], [example]
  • Multiple histograms: distribution of multiple variables [doc], [example]
  • Violin plot: distribution of multiple variables [doc], [example]
  • Correlation matrix: correlation between each columns of a dataset [doc], [example]
    • and the one-to-one scatter plots for the variables within the dataset [doc]
  • Count missing values: how many missing values are there in each column of the dataset [doc], [example]

3.4. Map plotting

  • Choropleth map (a.k.a., "heat map") of the United States, on both the state and county level [doc], [example]

3.5. Time series plotting

3.6. Miscellaneous

  • A get_colors() function that conveniently queries different color palettes [doc], [example]
  • A get_linespecs() function that generates distinct color/linestyle/linewidth combinations for plotting many lines together [doc], [example]
  • Two helper classes: Color and Multiple_Colors, which make querying and displaying colors more easily [doc], [example]
  • Plotting with error bounds, which displays error bounds as shaded areas [doc], [example]
  • trim_img(), which trims the white margins of the specified image file(s) [doc]
  • pad_img(), which pads image(s) with margins so that they meet a specified aspect ratio [doc]
  • plot_ranking(), which ranks a series of values and shows them as a bar chart [doc], [example]
  • visualize_cv_scores(), which visualizes cross-validation training/evaluation scores [doc], [example]

4. Gallery

4.1. One column of data

Using the "Titanic dataset" as example:

import pandas as pd
import plot_utils as pu
titanic = pd.read_csv('./examples/datasets/titanic3.csv')
pu.piechart(titanic['survived'], title='Suvived')
pu.discrete_histogram(titanic['pclass'], xlabel='Passenger ticket class')

Piechart: [doc], [example]

Discrete histogram: [doc], [example]

4.2. Two columns of data

Using the "Titanic dataset" as example:

titanic = pd.read_csv('./examples/datasets/titanic3.csv')
titanic.rename(index=str, columns={'pclass':'ticket_class'}, inplace=True)
titanic['embarked'] = titanic['embarked'].map(
    {'S':'Southampton', 'C':'Cherbourg', 'Q':'Queenstown'}
)

pu.bin_and_mean(titanic['age'], titanic['fare'], figsize=(5, 3))
pu.category_means(titanic['ticket_class'], titanic['fare'])
pu.positive_rate(titanic['ticket_class'], titanic['survived'], figsize=(5, 2))
pu.contingency_table(titanic['ticket_class'], titanic['embarked'], dropna=True, rot=0)

["bin-and-mean" doc] ["category means" doc] ["positive rate" doc] ["contingency table" doc] [All examples]

4.3. Multiple columns of data

4.3.1. 3D histograms

Useful for comparing multiple distributions:

iris = pd.read_csv('./examples/datasets/iris.csv')
pu.histogram3d(iris[['petal_width', 'petal_length', 'sepal_width', 'sepal_length']])

[doc], [example]

histogram_3d

4.3.2. Multi-histogram plots

Another useful tool to compare multiple distributions:

pu.hist_multi(iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]);

[doc], [example]

4.3.3. Violin plots

To compare multiple distributions:

pu.violin_plot(iris[['petal_width', 'petal_length', 'sepal_width', 'sepal_length']])

[doc], [example]

4.3.4. Correlation matrix

iris = pd.read_csv('./examples/datasets/iris.csv')
pu.plot_correlation(iris, scatter_plots=True)

The first figure shows the correlation (or "sample covariance") between each column. The second figure shows the scatter plots between each pair of columns.

[doc], [example]

4.3.5. Count missing values

To see how much data is missing in each column of a data set:

titanic = pd.read_csv('./examples/datasets/titanic3.csv')
pu.missing_value_counts(titanic)

[doc], [example]

Each bar corresponds to a column in titanic, and the numbers atop are the missing data counts for the corresponding column.

4.4. Choropleth maps (a.k.a., "heat maps")

4.4.1. State-level choropleth maps for the US

pu.choropleth_map_state(state_level_data)  # `state_level_data`: dict, pandas.DataFrame, or pandas.Series

[doc], [example]

choropleth_map_state

4.4.2. County-level choropleth maps for the US

pu.choropleth_map_county(county_level_data)  # `county_level_data`: dict, pandas.DataFrame, or pandas.Series

[doc], [example]

choropleth_map_county

4.5. Time series plotting

4.5.1. Single time series

df = pd.read_csv('./examples/datasets/Unemployment_rate_1976-2017.csv', index_col=0)
pu.plot_timeseries(df['CA'], ylabel='Unit: %', title='Unemployment rate, California')

[doc], [example]

4.5.2. Multiple time series

pu.plot_multiple_timeseries(df, ylabel='Unemployment rate [%]', ncol_legend=10)

[doc], [example]

4.6. Miscellaneous

4.6.1. get_colors() function

Easy querying of distinguishable color palettes.

colors = pu.get_colors(color_scheme='tab10', N=10)  # `colors`: a list containing 10 colors
pu.Multiple_Colors(colors).show()  # show colors as a palette

[doc], [example]

4.6.2. get_linespecs() function

Easy querying of distinguishable line specs.

line_specs = pu.get_linespecs(color_scheme='bw',range_linewidth=[3,8],priority='linewidth')
pu.linespecs_demo(line_specs)

[doc], [example]

[get_linespecs() doc]

4.6.3. Plot with error bounds

Plots data and error bounds on the same graph.

pu.plot_with_error_bounds(x, y, y_upper_bound, y_lower_bound)

[doc], [example]

4.6.4. Visualize cross-validation scores

pu.visualize_cv_scores(n_folds=4, cv_scores=[0.675, 0.702, 0.689, 0.653], holdout_score=0.6745);

[doc], [example]

5. Dependencies

  • Python 2.7 or 3.5+
  • matplotlib 1.5.0+, or 2.0.0+ (Version 2.1.0+ is strongly recommended.)
  • numpy: 1.11.0+
  • scipy: 0.19.0+
  • pandas: 0.20.0+
  • cycler: 0.10.0+
  • matplotlib/basemap: 1.0.7 (only if you want to plot the two choropleth maps)
  • PIL (only if you want to use trim_img() or pad_img())

6. Testing

To test plot_utils, run the ipython notebooks in the examples folder.

7. Aesthetics

The aesthetics of of the plot_utils module are matplotlib-styled by default, but it doesn't mean that you can't use your favorite styles in seaborn or ggplot2.

Unlike some plotting packages that enforces their own styles and restrict users from customizing, users of this module can adjust the figure styles freely: either from within matplotlib (https://matplotlib.org/devdocs/gallery/style_sheets/style_sheets_reference.html), or import seaborn and let seaborn take care of everything.

8. References

I did not built every function of this module entirely from scratch. I documented the sources that I referenced in the documentation of the corresponding functions.

9. Copyright and license

(c) 2017-2023, jsh9

License: GPL v3.0