A simple code for plotting figure, colorbar, and cropping with python

Overview

Python Plotting Tools

This repository provides a python code to generate figures (e.g., curves and barcharts) that can be used in the paper to show the results.

Dependencies: Python 3.+, numpy, and matplotlib.

Table of Contents

Preliminary

Layout of the diagram

The following shows a simple but complete diagram.

It contains the following common components. When creating a new diagram, we will modify these components to present our data:

  • Title
  • X-Label, xtick, and, xticklabel
  • Y-Label, ytick, and, yticklabel
  • Line, Marker, Legend
  • Grid

Sample configuration file

In this code, we define the appearance of the diagram with a configuration file. Then, we can plot the diagram by simply running:

python plot_diagram.py examples/demo/simple_plot.conf

The configuration file for the above simple plot is shown below with comments.

# CONFIGURATION FILE

# Comments start with '#'; 
# Parameters start with '!';
# If a parameter contains space, please replace the space with '&' for correct parsing
# For bool type, 1 is True else False

# Plot type: ploty|plotxy|plottwins
# ploty: The input data only contains Y values, the X values are generated as [0, ..., len(Y)]
# plotxy: The input data contains both X and Y values
# plottwins: The input data only contains Y values. Plot figure with two different Y-axis
! plot_type plotxy

# Figure format: pdf|jpg|png
! format pdf

# Canvas setting, fig size in inches
# https://matplotlib.org/devdocs/gallery/subplots_axes_and_figures/figure_size_units.html
! width 7
! height 3
! dpi 220

# Line and marker setting, different lines have different colors and marker shapes
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
# Example colors: 'r', 'k', 'b', 'g', 'y', 'm', 'c', 'tab:blue', 'tab:orange'
# Example markers: 'd', 'v', '1', '8', 'o', '^', '<', '>', 's', '*', 'p' 
! linewidth 1.5
! line_style -
! color tab:blue tab:orange tab:green
! markersize 4
! marker d v *

# Title and label setting 
# None indicates ignore; '&' is a placeholder for space;
# Eample font sizes: 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'
! title Simple&Plot
! title_font x-large
! xlabel x-Label
! xlabel_font x-large
! ylabel y-Label
! ylabel_font x-large

# Legend setting
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
# Example legend loc: 'best', 'upper left', 'upper right', 'lower left', 'lower right'
! legend Linear Quadratic Cubic
! legend_loc upper&left
! legend_font x-large
! legend_ncol 1

# Set grid on or off, 1 for on, 0 for off
! grid_on 1

# Data configuration
# Store the data values of a curve in a file, e.g., data.txt
# If have multiple curves, just list the file names one by one
! datafile data/linear.txt data/quadratic.txt data/cubic.txt

# Specify the maximum number of points, 
! max_point_num 1000

# set whether sort the data (None|ascend|descend), all x values should be the same for different curves
! sort_data None

Examples for Plotting Curves

Plot simple curves

The main difference between the following three configuration files is the number of curves.

# Figure at the below left
python plot_diagram.py examples/curve_simple_example/ploty_single_curve.conf

# Figure at the below middle
python plot_diagram.py examples/curve_simple_example/ploty_two_curves.conf

# Figure at the below right
python plot_diagram.py examples/curve_simple_example/ploty_multi_curves.conf

Plot dots

By adding "! draw_dot 1" in the .conf, we can plot dots instead of lines.

python plot_diagram.py examples/curve_simple_example/ploty_multi_dots.conf

Plot figure with customized xticklabel

We can manually set the xticklabel in the configuration file. e.g., adding "! xticklabel 2 4 9 18 30 36 45 60 90 180 $\infty$".

python plot_diagram.py examples/curve_custom_xtick/ploty_set_xtick.conf

We can also load the xticklabel from a file by setting the path, e.g., adding "! xtick_path data/merl_name.txt". We can rotate the xticklabel if they are too long by adding "! xtick_rot 90".

python plot_diagram.py examples/curve_custom_xtick/ploty_set_rotate_xtick.conf
# Remember that we can plot dots by setting draw_dot to 1 in the configuration file

Plot figure with two different Y-axes

By setting the plot_type to plottwins, we can draw the figure with two different Y-axes. But remember that this current implementation only supports two curves, one for each Y-axis.

python plot_diagram.py examples/curve_twin_y_axis/plottwins_yaxis.conf

Plot figure with customized legends

Note that this example is a hardcode for this specific legend pattern (i.e., two curves share the same legend).

python plot_diagram.py examples/curve_custom_legend/ploty_custom_legend.conf

Examples for Plot Functions

TODO.

Examples for Plotting Barchart

Layout of the barchart

The following shows a simple barchart.


It contains the following common components. When creating a new barchart, we will modify these components to present our data:

  • Title
  • X-Label, xtick, and, xticklabel
  • Y-Label, ytick, and, yticklabel
  • Bar, Text, Legend
  • Grid

The above barchart can be generated by running:

python plot_diagram.py examples/barchart_example1/simple_barchart.conf
Configuration file for the above barchart
# CONFIGURATION FILE

# Comments start with '#'; 
# Parameters start with '!';
# If a parameter contains space, please replace the space with '&' for correct parsing
# For bool type, 1 is True else False

# Plot type: ploty|plotxy|plottwins
# ploty: The input data only contains Y values, the X values are generated as [0, ..., len(Y)]
# plotxy: The input data contains both X and Y values
# plottwins: The input data only contains Y values. Plot figure with two different Y-axis
    ! plot_type plotbar

# Figure format: pdf|jpg|png
    ! format pdf

# Canvas setting, fig size in inches
# https://matplotlib.org/devdocs/gallery/subplots_axes_and_figures/figure_size_units.html
    ! width 5.5
    ! height 3
    ! dpi 220

# Data configuration
# Store the data values of the barchart in a single file, e.g., data.txt
# Each column corresponds to a group
# The number of row equals to the number of bars in a group 
    ! datafile data/bar_data_3group.txt

# IMPORTANT: Please remember to update the color, legend, xticklabel to match the input

# Bar setting
# Opacity sets the transparency of the bar, 0 indicates solid color
# Number of color and Opacity should equal to the bar numbers
    ! bar_width 0.3
    ! color tab:blue tab:red
    ! opacity 0.4 0.4
    ! y_min 0
    ! y_max 1

# xtick and ytick setting
    ! xticklabel vs.&Method1 vs.&Method2 vs.&Method3
# ! ytick 0 0.2 0.4 0.6 0.8 1.0
# ! yticklabel 0 20% 40% 60% 80% 100%

# Text setting
    ! put_text 1
    ! text_font 18
    ! percentage 0

# Title and label setting 
# None indicates ignore; '&' is a placeholder for space;
# Eample font sizes: 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'
    ! title Title
    ! title_font x-large
    ! xlabel x-Label
    ! xlabel_font x-large
    ! ylabel y-Label
    ! ylabel_font x-large

# Legend setting
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
# Example legend loc: 'best', 'upper left', 'upper right', 'lower left', 'lower right'
    ! legend Vote&Ours Vote&Others
    ! legend_loc upper&left
    ! legend_font xx-large
    ! legend_ncol 1
# You might need to tune the following bbox_to_anchor parameters to manually place the legends
    ! bbox_to_anchor -0.015 1.40

# Set grid on or off, 1 for on, 0 for off
    ! grid_on 1

Plot barchart with customized yticklabel

python plot_diagram.py examples/barchart_example1/simple_barchart_custom_ytick.conf

We set yticklabel in percentage, legend column number to 2, and show text in percentage, by adding the following to the config file.

! ytick 0 0.2 0.4 0.6 0.8 1.0
! yticklabel 0 20% 40% 60% 80% 100%
! legend_ncol 2
! percentage 1

Plot barchart with four bars in each group

python plot_diagram.py examples/barchart_example2/barchart_color.conf

Create Colorbar

We also provide a simple script to generate colorbar.

python img_tools/color_bar.py --colormap jet
python img_tools/color_bar.py --colormap jet --horizontal
python img_tools/color_bar.py --colormap viridis
python img_tools/color_bar.py --colormap viridis --horizontal

Crop Patches for Zoom-in Comparison

As it is very common to show zoom-in comparison between different methods in the paper, we provide a small image cropping scripts for this task.

By specifying the directory storing images, the desired box locations, and the colors, the following command can crop and highlight the boxes in the original images. However, you have to determine the locations of the boxes [left top bottom right] using other softwares.

python img_tools/image_cropper.py --in_dir examples/image_cropper_example/ -k '*.jpg' \
    --save_dir ROI --save_ext .jpg \
    --boxes 118 60 193 150 --boxes 371 452 431 521 --colors r g
# bash scripts/image_cropping.sh 


We can also add arrows onto the images to further highlight the differences.

python img_tools/image_cropper.py --in_dir examples/image_cropper_example/ --key '*.jpg' \
    --save_dir ROI_arrow --save_ext .jpg \
    --boxes 118 60 193 150 --boxes 371 452 431 521 --colors r g \
    --arrows 86 138 99 154 --arrows 502 412 488 393 --arrow_color r g


TODO: support selecting boxes in an interactive manner.

You might also like...
matplotlib: plotting with Python
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

🎨 Python Echarts Plotting Library
🎨 Python Echarts Plotting Library

pyecharts Python ❤️ ECharts = pyecharts English README 📣 简介 Apache ECharts (incubating) 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达

:small_red_triangle: Ternary plotting library for python with matplotlib
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

A Python library for plotting hockey rinks with Matplotlib.
A Python library for plotting hockey rinks with Matplotlib.

Hockey Rink A Python library for plotting hockey rinks with Matplotlib. Installation pip install hockey_rink Current Rinks The following shows the cus

termplotlib is a Python library for all your terminal plotting needs.
termplotlib is a Python library for all your terminal plotting needs.

termplotlib termplotlib is a Python library for all your terminal plotting needs. It aims to work like matplotlib. Line plots For line plots, termplot

MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.
MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit (VTK)
3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit (VTK)

PyVista Deployment Build Status Metrics Citation License Community 3D plotting and mesh analysis through a streamlined interface for the Visualization

A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews
A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

hvPlot A high-level plotting API for the PyData ecosystem built on HoloViews. Build Status Coverage Latest dev release Latest release Docs What is it?

Bokeh Plotting Backend for Pandas and GeoPandas
Bokeh Plotting Backend for Pandas and GeoPandas

Pandas-Bokeh provides a Bokeh plotting backend for Pandas, GeoPandas and Pyspark DataFrames, similar to the already existing Visualization feature of

Comments
  • suggestions

    suggestions

    Would you like to encapsulate this code into a python wrapper? That would be much more convenient for plotting. Just like original plt but with much more pretty layout.

    opened by pengzhangzhi 2
  • conf:format can't work

    conf:format can't work

    in plot_diagram.py parser.add_argument('--format', default='png', help='overwrite the save figure format, pdf|png|jpg') will cause the format in the conf to fail. should be parser.add_argument('--format', help='overwrite the save figure format, pdf|png|jpg')

    opened by byerose 1
  • run error

    run error

    run python plot_diagram.py examples/demo/simple_plot.conf error:

    Traceback (most recent call last):
      File "plot_diagram.py", line 8, in <module>
        sys.excepthook = ultratb.FormattedTB(call_pdb=True)
      File "/home/chen/.local/lib/python3.8/site-packages/IPython/core/ultratb.py", line 994, in __init__
        VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
      File "/home/chen/.local/lib/python3.8/site-packages/IPython/core/ultratb.py", line 638, in __init__
        TBTools.__init__(
      File "/home/chen/.local/lib/python3.8/site-packages/IPython/core/ultratb.py", line 242, in __init__
        self.pdb = debugger_cls()
    TypeError: 'NoneType' object is not callable
    

    environment;

    Package                Version             
    ---------------------- --------------------
    apturl                 0.5.2               
    argon2-cffi            21.3.0              
    argon2-cffi-bindings   21.2.0              
    asttokens              2.0.5               
    attrs                  21.4.0              
    backcall               0.2.0               
    bcrypt                 3.1.7               
    beautifulsoup4         4.11.1              
    bleach                 5.0.0               
    blinker                1.4                 
    Brlapi                 0.7.0               
    certifi                2019.11.28          
    cffi                   1.15.0              
    chardet                3.0.4               
    Click                  7.0                 
    colorama               0.4.3               
    command-not-found      0.3                 
    cryptography           2.8                 
    cupshelpers            1.0                 
    cycler                 0.11.0              
    dbus-python            1.2.16              
    debugpy                1.6.0               
    decorator              5.1.1               
    defer                  1.0.6               
    defusedxml             0.7.1               
    distro                 1.4.0               
    distro-info            0.23ubuntu1         
    duplicity              0.8.12.0            
    entrypoints            0.3                 
    executing              0.8.3               
    fasteners              0.14.1              
    fastjsonschema         2.15.3              
    fonttools              4.32.0              
    future                 0.18.2              
    httplib2               0.14.0              
    idna                   2.8                 
    importlib-resources    5.6.0               
    ipykernel              6.13.0              
    ipython                8.2.0               
    ipython-genutils       0.2.0               
    jedi                   0.18.1              
    Jinja2                 3.1.1               
    jsonschema             4.4.0               
    jupyter-client         7.2.2               
    jupyter-core           4.9.2               
    jupyterlab-pygments    0.2.1               
    keyring                18.0.1              
    kiwisolver             1.4.2               
    language-selector      0.1                 
    launchpadlib           1.10.13             
    lazr.restfulclient     0.14.2              
    lazr.uri               1.0.3               
    lockfile               0.12.2              
    louis                  3.12.0              
    macaroonbakery         1.3.1               
    Mako                   1.1.0               
    MarkupSafe             2.1.1               
    matplotlib             3.5.1               
    matplotlib-inline      0.1.3               
    mistune                0.8.4               
    monotonic              1.5                 
    nbclient               0.6.0               
    nbconvert              6.5.0               
    nbformat               5.3.0               
    nest-asyncio           1.5.5               
    netifaces              0.10.4              
    notebook               6.4.10              
    numpy                  1.22.3              
    oauthlib               3.1.0               
    olefile                0.46                
    packaging              21.3                
    pandocfilters          1.5.0               
    paramiko               2.6.0               
    parso                  0.8.3               
    pexpect                4.6.0               
    pickleshare            0.7.5               
    Pillow                 7.0.0               
    pip                    20.0.2              
    prometheus-client      0.14.1              
    prompt-toolkit         3.0.29              
    protobuf               3.6.1               
    psutil                 5.9.0               
    ptyprocess             0.7.0               
    pure-eval              0.2.2               
    pycairo                1.16.2              
    pycparser              2.21                
    pycups                 1.9.73              
    Pygments               2.11.2              
    PyGObject              3.36.0              
    PyJWT                  1.7.1               
    pymacaroons            0.13.0              
    PyNaCl                 1.3.0               
    pyparsing              3.0.8               
    pyRFC3339              1.1                 
    pyrsistent             0.18.1              
    python-apt             2.0.0+ubuntu0.20.4.7
    python-dateutil        2.8.2               
    python-debian          0.1.36ubuntu1       
    pytz                   2019.3              
    pyxdg                  0.26                
    PyYAML                 5.3.1               
    pyzmq                  22.3.0              
    reportlab              3.5.34              
    requests               2.22.0              
    requests-unixsocket    0.2.0               
    SecretStorage          2.3.1               
    Send2Trash             1.8.0               
    setuptools             45.2.0              
    simplejson             3.16.0              
    six                    1.14.0              
    soupsieve              2.3.2               
    ssh-import-id          5.10                
    stack-data             0.2.0               
    systemd-python         234                 
    terminado              0.13.3              
    tinycss2               1.1.1               
    tornado                6.1                 
    traitlets              5.1.1               
    ubuntu-advantage-tools 27.6                
    ubuntu-drivers-common  0.0.0               
    ufw                    0.36                
    unattended-upgrades    0.1                 
    urllib3                1.25.8              
    usb-creator            0.3.7               
    wadllib                1.3.3               
    wcwidth                0.2.5               
    webencodings           0.5.1               
    wheel                  0.34.2              
    xkit                   0.0.0               
    zipp                   3.8.0 
    
    opened by byerose 1
  • questions about plotting.

    questions about plotting.

    Prof. Chen, thanks so much for such a amazing tutorial. I have a question about the dpi. Sometimes I have to draw few .png picture with python and combine them in PPT for further beatifications. But .png files are very blur. How should I make them as clear as the vector-format (I know it is impossible, I just want them can be clearly read in a paper). Increasing dpi is a good idea? How much ipi is enough to satisfy my need? Thanks for your time~

    opened by pengzhangzhi 1
Owner
Guanying Chen
Guanying Chen
Simple plotting for Python. Python wrapper for D3xter - render charts in the browser with simple Python syntax.

PyDexter Simple plotting for Python. Python wrapper for D3xter - render charts in the browser with simple Python syntax. Setup $ pip install PyDexter

D3xter 31 Mar 6, 2021
This is a Cross-Platform Plot Manager for Chia Plotting that is simple, easy-to-use, and reliable.

Swar's Chia Plot Manager A plot manager for Chia plotting: https://www.chia.net/ Development Version: v0.0.1 This is a cross-platform Chia Plot Manage

Swar Patel 1.3k Dec 13, 2022
A deceptively simple plotting library for Streamlit

?? Plost A deceptively simple plotting library for Streamlit. Because you've been writing plots wrong all this time. Getting started pip install plost

Thiago Teixeira 192 Dec 29, 2022
Runtime analysis of code with plotting

Runtime analysis of code with plotting A quick comparison among Python, Cython, and the C languages A Programming Assignment regarding the Programming

Cena Ashoori 2 Dec 24, 2021
Python scripts for plotting audiograms and related data from Interacoustics Equinox audiometer and Otoaccess software.

audiometry Python scripts for plotting audiograms and related data from Interacoustics Equinox 2.0 audiometer and Otoaccess software. Maybe similar sc

Hamilton Lab at UT Austin 2 Jun 15, 2022
Analysis and plotting for motor/prop/ESC characterization, thrust vs RPM and torque vs thrust

esc_test This is a Python package used to plot and analyze data collected for the purpose of characterizing a particular propeller, motor, and ESC con

Alex Spitzer 1 Dec 28, 2021
NorthPitch is a python soccer plotting library that sits on top of Matplotlib

NorthPitch is a python soccer plotting library that sits on top of Matplotlib.

Devin Pleuler 30 Feb 22, 2022
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

Matplotlib Developers 16.7k Jan 8, 2023
🎨 Python Echarts Plotting Library

pyecharts Python ❤️ ECharts = pyecharts English README ?? 简介 Apache ECharts (incubating) 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达

pyecharts 13.1k Jan 3, 2023
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 611 Dec 29, 2022