A Python library for elegant data visualization

# Python plotting utilities: plot_utils

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

## 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.

## 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.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
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) ### 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] #### 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] #### 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] ### 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] #### 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.

(c) 2017-2023, jsh9

## Project details

This version 0.6.14 0.6.12 0.6.2

Uploaded source
Uploaded py2 py3
{"ft_lang_label":"__label__en","ft_lang_prob":0.59150237,"math_prob":0.6823383,"size":8677,"snap":"2023-14-2023-23","text_gpt3_token_len":2347,"char_repetition_ratio":0.11737576,"word_repetition_ratio":0.043437205,"special_character_ratio":0.2737121,"punctuation_ratio":0.21339174,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98921144,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"im_url_duplicate_count":[null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-05-29T09:50:38Z\",\"WARC-Record-ID\":\"<urn:uuid:696ba495-9a23-476c-8c61-d4294d2c47c0>\",\"Content-Length\":\"87389\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1e73e9e5-41d3-4c4a-8f21-72c222d5b8ee>\",\"WARC-Concurrent-To\":\"<urn:uuid:f6a42e81-e958-479b-8330-e1d83b2841f0>\",\"WARC-IP-Address\":\"151.101.0.223\",\"WARC-Target-URI\":\"https://pypi.org/project/plot-utils/\",\"WARC-Payload-Digest\":\"sha1:DHHYMTYU6NWUCLN6VNQHY2TDVAZZDBAO\",\"WARC-Block-Digest\":\"sha1:UIZSDQY4I2CYMKZ7OTOAIL7PD6BZZYYN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224644817.32_warc_CC-MAIN-20230529074001-20230529104001-00493.warc.gz\"}"}