Lesson · 40 min · Free
Matplotlib Visualization
Matplotlib Visualization body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; } code { font-fa
Matplotlib Visualization
Welcome to this lesson on Matplotlib Visualization , a fundamental skill for any data scientist, especially those working with biological and pharmaceutical data. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. While other libraries like Seaborn build on Matplotlib for more aesthetic and statistical plots, understanding Matplotlib's core functionality is crucial for fine-grained control over your figures. For pharmacy and biotech students, visualization is not just about making pretty graphs; it's about effectively communicating complex experimental results, drug efficacy, dose-response curves, and patient outcomes. Clear and accurate visualizations can highlight trends, outliers, and statistical significance, aiding in critical decision-making processes. We will focus on creating common plot types essential for scientific data analysis, such as line plots for time-series data or dose-response curves, and scatter plots for exploring relationships between variables. We'll also cover customizing plot elements to ensure your visualizations are informative and publication-ready.
Basic Plotting with Matplotlib
The most common way to use Matplotlib is through its pyplot module, which provides a MATLAB-like interface. We typically import it as plt . Let's start by creating a simple line plot, which is excellent for showing trends over time or concentration gradients, typical in pharmacokinetic studies or cell growth assays. import matplotlib.pyplot as plt import numpy as np # Sample data: Time points (e.g., hours) and drug concentration (e.g., ng/mL) time_points = np.array([0, 1, 2, 4, 6, 8, 12, 24]) drug_concentration = np.array([100, 95, 80, 60, 40, 25, 10, 2]) # Example of drug decay # Create a figure and an axes object fig, ax = plt.subplots(figsize=(8, 5)) # figsize sets the width and height of the figure in inches # Plot the data ax.plot(time_points, drug_concentration, marker='o', linestyle='-', color='blue', label='Drug X Concentration') # Add labels and title ax.set_xlabel('Time (Hours)') ax.set_ylabel('Drug Concentration (ng/mL)') ax.set_title('Drug X Pharmacokinetic Profile') # Add a legend ax.legend() # Add a grid for better readability ax.grid(True, linestyle='--', alpha=0.7) # Display the plot plt.show() In this example, we first import matplotlib.pyplot and numpy . We then define our data. The plt.subplots() function is a powerful way to create a figure and a set of subplots (axes) simultaneously. We then use ax.plot() to draw our line. Notice the use of marker , linestyle , and color to customize the line. Finally, ax.set_xlabel() , ax.set_ylabel() , and ax.set_title() are used to add descriptive labels, which are crucial for interpreting scientific graphs.
Scatter Plots for Relationship Exploration
Scatter plots are invaluable for visualizing the relationship between two continuous variables. For instance, in drug discovery, you might plot drug dosage against a biological response, or gene expression levels against disease severity. Let's look at an example comparing two different treatment groups. import matplotlib.pyplot as plt import numpy as np # Sample data: Dosage and efficacy for two hypothetical treatments np.random.seed(42) # for reproducibility # Treatment A: Lower efficacy, more variability dosage_A = np.random.rand(50) * 100 # Random dosage between 0 and 100 efficacy_A = 0.5 * dosage_A + np.random.randn(50) * 20 + 10 # Linear trend + noise # Treatment B: Higher efficacy, less variability dosage_B = np.random.rand(50) * 100 efficacy_B = 0.8 * dosage_B + np.random.randn(50) * 10 + 20 # Create a figure and an axes object fig, ax = plt.subplots(figsize=(9, 6)) # Plot Treatment A data ax.scatter(dosage_A, efficacy_A, color='red', alpha=0.6, label='Treatment A Response') # Plot Treatment B data ax.scatter(dosage_B, efficacy_B, color='green', alpha=0.6, label='Treatment B Response') # Add labels and title ax.set_xlabel('Dosage (mg)') ax.set_ylabel('Efficacy (% Response)') ax.set_title('Comparison of Drug Efficacy by Dosage for Two Treatments') # Add a legend ax.legend() # Add a grid ax.grid(True, linestyle=':', alpha=0.6) # Set limits for better visualization if needed ax.set_xlim(0, 110) ax.set_ylim(0, 100) # Display the plot plt.show() In this scatter plot example, we generate data for two hypothetical treatments. We use ax.scatter() to plot the points. The alpha parameter controls the transparency of the points, which is useful when dealing with overlapping data points. By plotting both treatments on the same axes, we can visually compare their dose-response characteristics. This kind of visualization is critical for comparing drug candidates or different formulations.
Key Takeaways
Matplotlib is foundational: It provides the building blocks for almost all Python plotting. pyplot module: The primary interface for most plotting tasks (imported as plt ). Figure and Axes: Understand the distinction; the Figure is the overall window, and Axes are the individual plots within it. plt.subplots() is a common way to get both. Customization is key: Use xlabel() , ylabel() , title() , legend() , color , marker , linestyle , and alpha to make plots informative and clear. Plot Types: Line plots for trends (e.g., time-series, dose-response) and scatter plots for relationships between variables are frequently used in biotech/pharmacy.
Practice Exercise: Visualize Gene Expression Data
Imagine you have data representing the expression levels of a particular gene (e.g., in relative fluorescence units, RFU) across different experimental conditions or patient groups. Your task is to create a bar chart to compare the average gene expression levels between three hypothetical groups: 'Control', 'Treated A', and 'Treated B'. Use Matplotlib to: Generate some sample data for the mean gene expression and standard deviation for each group. Create a bar chart showing the mean expression for each group. Add error bars to represent the standard deviation (you can use the yerr argument in ax.bar() ). Label the x-axis with group names and the y-axis as 'Gene Expression (RFU)'. Give the plot a descriptive title, like 'Gene Expression Levels Across Experimental Groups'. Add a grid to the plot for better readability. This exercise will solidify your understanding of creating categorical comparisons with error bars, a common requirement in presenting biological data.
Watch the full lesson — free
This topic is part of Python for Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →