LogoLogo
LogoLogo
  • The Barbara K. Ostrom (1978) Bioinformatics and Computing Facility
  • Computing Resources
    • Active Data Storage
    • Archive Data Storage
    • Luria Cluster
      • FAQs
    • Other Resources
  • Bioinformatics Topics
    • Tools - A Basic Bioinformatics Toolkit
      • Getting more out of Microsoft Excel
      • Bioinformatics Applications of Unix
        • Unix commands applied to bioinformatics
        • Manipulate NGS files using UNIX commands
        • Manipulate alignment files using UNIX commands
      • Alignments and Mappers
      • Relational databases
        • Running Joins on Galaxy
      • Spotfire
    • Tasks - Bioinformatics Methods
      • UCSC Genome Bioinformatics
        • Interacting with the UCSC Genome Browser
        • Obtaining DNA sequence from the UCSC Database
        • Obtaining genomic data from the UCSC database using table browser queries
        • Filtering table browser queries
        • Performing a BLAT search
        • Creating Custom Tracks
        • UCSC Intersection Queries
        • Viewing cross-species alignments
        • Galaxy
          • Intro to Galaxy
          • Galaxy NGS Illumina QC
          • Galaxy NGS Illumina SE Mapping
          • Galaxy SNP Interval Data
        • Editing and annotation gene structures with Argo
      • GeneGO MetaCore
        • GeneGo Introduction
        • Loading Data Into GeneGO
        • Data Management in GeneGO
        • Setting Thresholds and Background Sets
        • Search And Browse Content Tab
        • Workflows and Reports Tab
        • One-click Analysis Tab
        • Building Network for Your Experimental Data
      • Functional Annotation of Gene Lists
      • Multiple Sequence Alignment
        • Clustalw2
      • Phylogenetic analysis
        • Neighbor Joining method in Phylip
      • Microarray data processing with R/Bioconductor
    • Running Jupyter notebooks on luria cluster nodes
  • Data Management
    • Globus
  • Mini Courses
    • Schedule
      • Previous Teaching
    • Introduction to Unix and KI Computational Resources
      • Basic Unix
        • Why Unix?
        • The Unix Tree
        • The Unix Terminal and Shell
        • Anatomy of a Unix Command
        • Basic Unix Commands
        • Output Redirection and Piping
        • Manual Pages
        • Access Rights
        • Unix Text Editors
          • nano
          • vi / vim
          • emacs
        • Shell Scripts
      • Software Installation
        • Module
        • Conda Environment
      • Slurm
    • Introduction to Unix
      • Why Unix?
      • The Unix Filesystem
        • The Unix Tree
        • Network Filesystems
      • The Unix Shell
        • About the Unix Shell
        • Unix Shell Manual Pages
        • Using the Unix Shell
          • Viewing the Unix Tree
          • Traversing the Unix Tree
          • Editing the Unix Tree
          • Searching the Unix Tree
      • Files
        • Viewing File Contents
        • Creating and Editing Files
        • Manipulating Files
        • Symbolic Links
        • File Ownership
          • How Unix File Ownership Works
          • Change File Ownership and Permissions
        • File Transfer (in-progress)
        • File Storage and Compression
      • Getting System Information
      • Writing Scripts
      • Schedule Scripts Using Crontab
    • Advanced Utilization of IGB Computational Resources
      • High Performance Computing Clusters
      • Slurm
        • Checking the Status of Computing Nodes
        • Submitting Jobs / Slurm Scripts
        • Interactive Sessions
      • Package Management
        • The System Package Manager
        • Environment Modules
        • Conda Environments
      • SSH Port Forwarding
        • SSH Port Forwarding Jupyter Notebooks
      • Containerization
        • Docker
          • Docker Installation
          • Running Docker Images
          • Building Docker Images
        • Singularity
          • Differences from Docker
          • Running Images in Singularity
      • Running Nextflow / nf-core Pipelines
    • Python
      • Introduction to Python for Biologists
        • Interactive Python
        • Types
          • Strings
          • Lists
          • Tuples
          • Dictionaries
        • Control Flow
        • Loops
          • For Loops
          • While Loops
        • Control Flows and Loops
        • Storing Programs for Re-use
        • Reading and Writing Files
        • Functions
      • Biopython
        • About Biopython
        • Quick Start
          • Basic Sequence Analyses
          • SeqRecord
          • Sequence IO
          • Exploration of Entrez Databases
        • Example Projects
          • Coronavirus Exploration
          • Translating a eukaryotic FASTA file of CDS entries
        • Further Resources
      • Machine Learning with Python
        • About Machine Learning
        • Hands-On
          • Project Introduction
          • Supervised Approaches
            • The Logistic Regression Model
            • K-Nearest Neighbors
          • Unsupervised Approaches
            • K-Means Clustering
          • Further Resources
      • Data Processing with Python
        • Pandas
          • About Pandas
          • Making DataFrames
          • Inspecting DataFrames
          • Slicing DataFrames
          • Selecting from DataFrames
          • Editing DataFrames
        • Matplotlib
          • About Matplotlib
          • Basic Plotting
          • Advanced Plotting
        • Seaborn
          • About Seaborn
          • Basic Plotting
          • Visualizing Statistics
          • Visualizing Proteomics Data
          • Visualizing RNAseq Data
    • R
      • Intro to R
        • Before We Start
        • Getting to Know R
        • Variables in R
        • Functions in R
        • Data Manipulation
        • Simple Statistics in R
        • Basic Plotting in R
        • Advanced Plotting in R
        • Writing Figures to a File
        • Further Resources
    • Version Control with Git
      • About Version Control
      • Setting up Git
      • Creating a Repository
      • Tracking Changes
        • Exercises
      • Exploring History
        • Exercises
      • Ignoring Things
      • Remotes in Github
      • Collaborating
      • Conflicts
      • Open Science
      • Licensing
      • Citation
      • Hosting
      • Supplemental
Powered by GitBook

MIT Resources

  • https://accessibility.mit.edu

Massachusetts Institute of Technology

On this page
  • Getting Ready
  • Advanced Line Plot
  • Advanced Bar Plots
  • Advanced Histogram
  • Scatter Plot
  • Parallel Coordinates
  • Andrews Curves
  • RadViz

Was this helpful?

Export as PDF
  1. Mini Courses
  2. Python
  3. Data Processing with Python
  4. Matplotlib

Advanced Plotting

PreviousBasic PlottingNextSeaborn

Last updated 1 year ago

Was this helpful?

Getting Ready

dat2=pd.read_csv("C:\\Users\duan\Desktop\PythonDataProcessingVisualization\meanByClass.txt", sep='\s+')
dat2

Explore a fake gene expression data modified from iris.csv

rpkm=pd.read_csv("C:\\Users\duan\Desktop\PythonDataProcessingVisualization\\fakeExpressionDat.csv")
rpkm

Advanced Line Plot

plt.figure(); dat2.plot(); plt.legend(loc='best')

Get rid of the legend

dat2.plot(legend=False)

Separate the features

dat2.plot(subplots=True, figsize=(6, 6)); plt.legend(loc='best')

Plotting on a Secondary Y-axis

plt.figure()
dat2.WtTypeA.plot(color="b")
dat2.WtTypeB.plot(color="turquoise")
dat2.KOTypeA.plot(color="r")
dat2.KOTypeB.plot(color="pink")
dat2.replicate.plot(secondary_y=True, style='g')

Plot a subset of columns

plt.figure()
dat2.WtTypeA.plot(color="b")
dat2.WtTypeB.plot(color="turquoise")
dat2.KOTypeA.plot(color="r")
dat2.KOTypeB.plot(color="pink")

Selective Plotting on Secondary Y-axis

plt.figure()
dat3=dat2.drop(['replicate'], axis = 1)
ax = dat3.plot(secondary_y=['wtTypeA', 'KOTypeA'])
ax.set_ylabel('TypeB scale')
ax.right_ax.set_ylabel('TypeA scale')

Targeting different subplots by passing an ax argument

fig, axes = plt.subplots(nrows=2, ncols=2)
dat2['WtTypeA'].plot(ax=axes[0,0]); axes[0,0].set_title('WtTypeA')
dat2['KOTypeA'].plot(ax=axes[0,1]); axes[0,1].set_title('KOTypeA')
dat2['WtTypeB'].plot(ax=axes[1,0]); axes[1,0].set_title('WtTypeB')
dat2['KOTypeB'].plot(ax=axes[1,1]); axes[1,1].set_title('KOTypeB')

Adjusting spacing between subplots

fig, axes = plt.subplots(nrows=2, ncols=2)
dat2['WtTypeA'].plot(ax=axes[0,0]); axes[0,0].set_title('WtTypeA')
dat2['KOTypeA'].plot(ax=axes[0,1]); axes[0,1].set_title('KOTypeA')
dat2['WtTypeB'].plot(ax=axes[1,0]); axes[1,0].set_title('WtTypeB')
dat2['KOTypeB'].plot(ax=axes[1,1]); axes[1,1].set_title('KOTypeB')
plt.subplots_adjust(left=0.1,
                    bottom=0.1,
                    right=0.9,
                    top=0.9,
                    wspace=0.4,
                    hspace=0.4)

Advanced Bar Plots

Looking at one replicate a time

plt.figure();
dat2.iloc[1].plot(kind='bar'); plt.axhline(0, color='k')

Looking at all replicates at the same time

plt.figure();
dat2.plot(kind='bar'); plt.axhline(0, color='k')
plt.figure();
dat2.plot(kind='bar', colormap='Greens')

stacked boxes

dat3.plot(kind='bar', stacked=True);

Advanced Histogram

plt.figure()
dat.hist(by="genotype", figsize=(6, 4),bins=20)

Scatter Plot

from pandas.plotting import scatter_matrix
rpkm=pd.read_csv("C:\\Users\duan\Desktop\IntroductionToMatplotlib\\fakeExpressionDat.csv")
rpkm
scatter_matrix(rpkm, alpha=0.9, figsize=(6, 6), diagonal='kde')

Parallel Coordinates

Parallel coordinates is a plotting technique for plotting multivariate data. It allows one to see clusters in data and to estimate other statistics visually. Using parallel coordinates points are represented as connected line segments. Each vertical line represents one attribute. One set of connected line segments represents one data point. Points that tend to cluster will appear closer together

from pandas.plotting import parallel_coordinates
plt.figure()
parallel_coordinates(rpkm, 'pathway')
from pandas.plotting import parallel_coordinates
plt.figure()
parallel_coordinates(rpkm, 'pathway',colormap='gist_rainbow')
from pandas.plotting import parallel_coordinates
plt.figure()
parallel_coordinates(rpkm, 'pathway',colormap='spring')
from pandas.plotting import parallel_coordinates
plt.figure()
parallel_coordinates(rpkm, 'pathway',colormap='autumn')

Andrews Curves

Andrews Curves are smoothed versions of Parallel Coordinates

from pandas.plotting import andrews_curves
plt.figure()
andrews_curves(rpkm, 'pathway')
plt.show()

A potential issue when plotting a large number of columns is that it can be difficult to distinguish some series due to repetition in the default colors. To remedy this, we can either loop through different colors using rainbow() function. Or DataFrame plotting supports the use of the colormap= argument, which accepts either a Matplotlib colormap or a string that is a name of a colormap registered with Matplotlib

plt.figure()
andrews_curves(rpkm, 'pathway',color = [cm.rainbow(i) for i in np.linspace(0, 1, 3)])
plt.show()
plt.figure()
andrews_curves(rpkm, 'pathway',colormap='jet')
plt.show()
plt.figure()
andrews_curves(rpkm, 'pathway',colormap="winter")
plt.show()

RadViz

from pandas.plotting import radviz
plt.figure()
radviz(rpkm, 'pathway')
plt.show()
from pandas.plotting import radviz
plt.figure()
radviz(rpkm, 'pathway',colormap="Set1")
plt.show()