SlideShare a Scribd company logo
1 of 10
Plotting heatmap with
matplotlib/seaborn
February 2nd 2022
Method 1: matplotlib (auto)
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random(( 12 , 12 ))
plt.imshow( data , cmap = 'autumn',interpolation = 'nearest' )
plt.title( "2-D Heat Map" )
plt.show()
https://www.geeksforgeeks.org/how-to-draw-2d-heatmap-using-matplotlib-in-python/
Method 2: seaborn (auto)
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
https://seaborn.pydata.org/generated/seaborn.heatmap.html
Method 2: seaborn (auto + label)
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights)
https://seaborn.pydata.org/generated/seaborn.heatmap.html
Method 2: seaborn (auto + label + annotation)
flights = sns.load_dataset("flights")
ax = sns.heatmap(flights, annot=True, fmt="d")
ax = sns.heatmap(flights)
https://seaborn.pydata.org/generated/seaborn.heatmap.html
Method 2: Two heatmaps
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import gridspec
fig = plt.figure(figsize=(12, 10), dpi=300)
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0 = sns.heatmap(terms, cmap=cmap, cbar=False)
ax1 = plt.subplot(gs[1])
ax1 = sns.heatmap(ground_truth, cmap=cmap, yticklabels=False,
cbar_kws={'shrink': 2.0, 'label': 'Quantile of term'})
Method 3: matplotlib (manual)
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon, Rectangle
from matplotlib.collections import PatchCollection
fig, ax = plt.subplots()
patch1 = []
for y_corr in reversed(range(11)):
for x_corr in range(11):
patch1.append(Rectangle((x_corr,y_corr),1,1))
p = PatchCollection(patch1, cmap='RdYlBu', alpha=0.6)
p.set_edgecolor('black')
# map color
color = df.values.flatten()
p.set_array(np.array(color))
ax.add_collection(p)
…
ax.set_yticklabels(...)
ax.set_ylabel('Query extension (bp)')
…
col = plt.colorbar(p, cax = cax, format=ticker.FuncFormatter(fmt))
col.ax.set_ylabel("Geometric mean of q-value")
…
ax.add_patch(Rectangle((5, 4), 1, 1, fill=False, edgecolor='lawngreen', lw=3))
Heatmap
Label
Color bar
Highlight rectangle
Method3: Heatmap with two colors
Heatmap with two colors
from matplotlib.patches import Polygon, Rectangle
for y_corr in reversed(range(10)):
for x_corr in range(10):
index1 = [[x_corr, y_corr], [x_corr + 1, y_corr + 1], [x_corr, y_corr + 1]]
patch1.append(plt.Polygon(index1))
Heatmap with two colors
added manually !!!

More Related Content

More from Hoffman Lab

File searching tools
File searching toolsFile searching tools
File searching toolsHoffman Lab
 
Better BibTeX (BBT) for Zotero
Better BibTeX (BBT) for ZoteroBetter BibTeX (BBT) for Zotero
Better BibTeX (BBT) for ZoteroHoffman Lab
 
Awk primer and Bioawk
Awk primer and BioawkAwk primer and Bioawk
Awk primer and BioawkHoffman Lab
 
Terminals and Shells
Terminals and ShellsTerminals and Shells
Terminals and ShellsHoffman Lab
 
BioRender & Glossary/Acronym
BioRender & Glossary/AcronymBioRender & Glossary/Acronym
BioRender & Glossary/AcronymHoffman Lab
 
BioSyntax: syntax highlighting for computational biology
BioSyntax: syntax highlighting for computational biologyBioSyntax: syntax highlighting for computational biology
BioSyntax: syntax highlighting for computational biologyHoffman Lab
 
Get Good With Git
Get Good With GitGet Good With Git
Get Good With GitHoffman Lab
 
Tech Talk: UCSC Genome Browser
Tech Talk: UCSC Genome BrowserTech Talk: UCSC Genome Browser
Tech Talk: UCSC Genome BrowserHoffman Lab
 
MultiQC: summarize analysis results for multiple tools and samples in a singl...
MultiQC: summarize analysis results for multiple tools and samples in a singl...MultiQC: summarize analysis results for multiple tools and samples in a singl...
MultiQC: summarize analysis results for multiple tools and samples in a singl...Hoffman Lab
 
dreamRs: interactive ggplot2
dreamRs: interactive ggplot2dreamRs: interactive ggplot2
dreamRs: interactive ggplot2Hoffman Lab
 
Basic Cryptography & Security
Basic Cryptography & SecurityBasic Cryptography & Security
Basic Cryptography & SecurityHoffman Lab
 
Intervene: a tool for intersection and visualization of multiple gene or geno...
Intervene: a tool for intersection and visualization of multiple gene or geno...Intervene: a tool for intersection and visualization of multiple gene or geno...
Intervene: a tool for intersection and visualization of multiple gene or geno...Hoffman Lab
 
Evaluating machine learning claims
Evaluating machine learning claimsEvaluating machine learning claims
Evaluating machine learning claimsHoffman Lab
 
Introduction to proteomics
Introduction to proteomicsIntroduction to proteomics
Introduction to proteomicsHoffman Lab
 
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updates
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updatesTopics in TeX and LaTeX: Selected packages, programming, and Overleaf updates
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updatesHoffman Lab
 
Conda and Bioconda
Conda and BiocondaConda and Bioconda
Conda and BiocondaHoffman Lab
 
TPOT: The data science assistant
TPOT: The data science assistantTPOT: The data science assistant
TPOT: The data science assistantHoffman Lab
 
Transferring data: best practices, Globus Online, and Compute Canada infrastr...
Transferring data: best practices, Globus Online, and Compute Canada infrastr...Transferring data: best practices, Globus Online, and Compute Canada infrastr...
Transferring data: best practices, Globus Online, and Compute Canada infrastr...Hoffman Lab
 

More from Hoffman Lab (20)

File searching tools
File searching toolsFile searching tools
File searching tools
 
Better BibTeX (BBT) for Zotero
Better BibTeX (BBT) for ZoteroBetter BibTeX (BBT) for Zotero
Better BibTeX (BBT) for Zotero
 
Awk primer and Bioawk
Awk primer and BioawkAwk primer and Bioawk
Awk primer and Bioawk
 
Terminals and Shells
Terminals and ShellsTerminals and Shells
Terminals and Shells
 
BioRender & Glossary/Acronym
BioRender & Glossary/AcronymBioRender & Glossary/Acronym
BioRender & Glossary/Acronym
 
Linters in R
Linters in RLinters in R
Linters in R
 
BioSyntax: syntax highlighting for computational biology
BioSyntax: syntax highlighting for computational biologyBioSyntax: syntax highlighting for computational biology
BioSyntax: syntax highlighting for computational biology
 
Get Good With Git
Get Good With GitGet Good With Git
Get Good With Git
 
Tech Talk: UCSC Genome Browser
Tech Talk: UCSC Genome BrowserTech Talk: UCSC Genome Browser
Tech Talk: UCSC Genome Browser
 
MultiQC: summarize analysis results for multiple tools and samples in a singl...
MultiQC: summarize analysis results for multiple tools and samples in a singl...MultiQC: summarize analysis results for multiple tools and samples in a singl...
MultiQC: summarize analysis results for multiple tools and samples in a singl...
 
dreamRs: interactive ggplot2
dreamRs: interactive ggplot2dreamRs: interactive ggplot2
dreamRs: interactive ggplot2
 
Basic Cryptography & Security
Basic Cryptography & SecurityBasic Cryptography & Security
Basic Cryptography & Security
 
Intervene: a tool for intersection and visualization of multiple gene or geno...
Intervene: a tool for intersection and visualization of multiple gene or geno...Intervene: a tool for intersection and visualization of multiple gene or geno...
Intervene: a tool for intersection and visualization of multiple gene or geno...
 
Evaluating machine learning claims
Evaluating machine learning claimsEvaluating machine learning claims
Evaluating machine learning claims
 
Introduction to proteomics
Introduction to proteomicsIntroduction to proteomics
Introduction to proteomics
 
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updates
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updatesTopics in TeX and LaTeX: Selected packages, programming, and Overleaf updates
Topics in TeX and LaTeX: Selected packages, programming, and Overleaf updates
 
Conda and Bioconda
Conda and BiocondaConda and Bioconda
Conda and Bioconda
 
Elixir and OTP
Elixir and OTPElixir and OTP
Elixir and OTP
 
TPOT: The data science assistant
TPOT: The data science assistantTPOT: The data science assistant
TPOT: The data science assistant
 
Transferring data: best practices, Globus Online, and Compute Canada infrastr...
Transferring data: best practices, Globus Online, and Compute Canada infrastr...Transferring data: best practices, Globus Online, and Compute Canada infrastr...
Transferring data: best practices, Globus Online, and Compute Canada infrastr...
 

Recently uploaded

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Plotting heatmap with matplotlib/seaborn

  • 2. Method 1: matplotlib (auto) import numpy as np import matplotlib.pyplot as plt data = np.random.random(( 12 , 12 )) plt.imshow( data , cmap = 'autumn',interpolation = 'nearest' ) plt.title( "2-D Heat Map" ) plt.show() https://www.geeksforgeeks.org/how-to-draw-2d-heatmap-using-matplotlib-in-python/
  • 3. Method 2: seaborn (auto) import numpy as np; np.random.seed(0) import seaborn as sns; sns.set_theme() uniform_data = np.random.rand(10, 12) ax = sns.heatmap(uniform_data) https://seaborn.pydata.org/generated/seaborn.heatmap.html
  • 4. Method 2: seaborn (auto + label) flights = sns.load_dataset("flights") flights = flights.pivot("month", "year", "passengers") ax = sns.heatmap(flights) https://seaborn.pydata.org/generated/seaborn.heatmap.html
  • 5. Method 2: seaborn (auto + label + annotation) flights = sns.load_dataset("flights") ax = sns.heatmap(flights, annot=True, fmt="d") ax = sns.heatmap(flights) https://seaborn.pydata.org/generated/seaborn.heatmap.html
  • 6. Method 2: Two heatmaps import matplotlib.pyplot as plt import seaborn as sns from matplotlib import gridspec fig = plt.figure(figsize=(12, 10), dpi=300) gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) ax0 = plt.subplot(gs[0]) ax0 = sns.heatmap(terms, cmap=cmap, cbar=False) ax1 = plt.subplot(gs[1]) ax1 = sns.heatmap(ground_truth, cmap=cmap, yticklabels=False, cbar_kws={'shrink': 2.0, 'label': 'Quantile of term'})
  • 7. Method 3: matplotlib (manual) import matplotlib.pyplot as plt from matplotlib.patches import Polygon, Rectangle from matplotlib.collections import PatchCollection fig, ax = plt.subplots() patch1 = [] for y_corr in reversed(range(11)): for x_corr in range(11): patch1.append(Rectangle((x_corr,y_corr),1,1)) p = PatchCollection(patch1, cmap='RdYlBu', alpha=0.6) p.set_edgecolor('black') # map color color = df.values.flatten() p.set_array(np.array(color)) ax.add_collection(p) … ax.set_yticklabels(...) ax.set_ylabel('Query extension (bp)') … col = plt.colorbar(p, cax = cax, format=ticker.FuncFormatter(fmt)) col.ax.set_ylabel("Geometric mean of q-value") … ax.add_patch(Rectangle((5, 4), 1, 1, fill=False, edgecolor='lawngreen', lw=3)) Heatmap Label Color bar Highlight rectangle
  • 9. Heatmap with two colors from matplotlib.patches import Polygon, Rectangle for y_corr in reversed(range(10)): for x_corr in range(10): index1 = [[x_corr, y_corr], [x_corr + 1, y_corr + 1], [x_corr, y_corr + 1]] patch1.append(plt.Polygon(index1))
  • 10. Heatmap with two colors added manually !!!