Lesson · 40 min · Free
Matplotlib Visualization Basics
Matplotlib Visualization Basics body { font-family: sans-serif; line-height: 1.6; color: #333; } h1, h2 { color: #0056b3; } pre { background-color: #f4f4f4; border: 1px solid #ddd; padding: 10px; overflow-x: auto; } code
Matplotlib Visualization Basics
Welcome to the Matplotlib Visualization Basics lesson! In the realm of pharmacy and biotechnology, data visualization is not just an aesthetic choice; it's a critical tool for interpreting experimental results, communicating findings, and making informed decisions. Whether you're analyzing drug efficacy trials, gene expression patterns, or protein folding simulations, effectively presenting your data can highlight trends, outliers, and relationships that might otherwise remain hidden. Matplotlib is the foundational plotting library in Python, offering a highly flexible and powerful environment for creating static, animated, and interactive visualizations. While other libraries like Seaborn build upon Matplotlib for more statistically-oriented plots, understanding Matplotlib's core principles is essential for fine-tuning your visualizations and creating custom plots tailored to the specific needs of scientific research. At its core, Matplotlib operates on a hierarchical structure. The top-level container is the Figure , which can be thought of as the entire window or page on which plots are drawn. Within a Figure , you can have one or more Axes objects. An Axes is the actual region where the data is plotted, including the x and y-axis, labels, and tick marks. This distinction is crucial: a Figure can contain multiple Axes , allowing for subplots and complex layouts. Let's start with a simple line plot, a common visualization for showing trends over time or across a continuum, such as drug concentration over time or reaction rates at different temperatures. We'll use numpy to generate some sample data, mimicking a typical pharmacokinetic profile. import matplotlib.pyplot as plt import numpy as np # Sample data: mimicking drug concentration over time time = np.linspace(0, 24, 100) # 0 to 24 hours, 100 points initial_concentration = 100 decay_rate = 0.15 # per hour concentration = initial_concentration * np.exp(-decay_rate * time) # Create a figure and an axes object fig, ax = plt.subplots(figsize=(10, 6)) # figsize sets the width and height of the figure in inches # Plot the data ax.plot(time, concentration, color='purple', linestyle='-', linewidth=2, label='Drug Concentration') # Add titles and labels for clarity ax.set_title('Pharmacokinetic Profile: Drug Concentration Over Time', fontsize=16) ax.set_xlabel('Time (hours)', fontsize=12) ax.set_ylabel('Concentration (ng/mL)', fontsize=12) ax.legend(fontsize=10) # Display the legend ax.grid(True, linestyle='--', alpha=0.7) # Add a grid for easier reading # Customize tick marks ax.tick_params(axis='both', which='major', labelsize=10) # Display the plot plt.show() In the example above, plt.subplots() is a convenient function that creates both a Figure and a set of Axes objects at once. We then use methods associated with the ax object (like ax.plot() , ax.set_title() ) to customize our plot. This object-oriented approach is generally preferred for more complex plots as it provides greater control. Beyond line plots, scatter plots are incredibly useful for visualizing the relationship between two variables, often used in dose-response curves, correlation analyses, or comparing experimental conditions. Let's create a scatter plot to visualize the relationship between two hypothetical biological measurements, perhaps gene expression levels under two different conditions. import matplotlib.pyplot as plt import numpy as np # Sample data: gene expression levels under two conditions np.random.seed(42) # for reproducibility condition_A_expression = np.random.normal(loc=10, scale=2, size=50) # Mean 10, Std Dev 2 condition_B_expression = condition_A_expression * 0.8 + np.random.normal(loc=1, scale=1, size=50) # Some correlation + noise # Create a figure and an axes object fig, ax = plt.subplots(figsize=(8, 8)) # Plot the data as a scatter plot ax.scatter(condition_A_expression, condition_B_expression, s=80, # size of the markers alpha=0.7, # transparency color='skyblue', # color of the markers edgecolor='blue', # border color of the markers label='Gene Expression Comparison') # Add titles and labels ax.set_title('Gene Expression Levels: Condition A vs. Condition B', fontsize=14) ax.set_xlabel('Expression Level - Condition A', fontsize=12) ax.set_ylabel('Expression Level - Condition B', fontsize=12) ax.legend(fontsize=10) ax.grid(True, linestyle=':', alpha=0.6) # Set equal limits for x and y axes for a square plot to easily compare scales max_val = max(ax.get_xlim()[1], ax.get_ylim()[1]) min_val = min(ax.get_xlim()[0], ax.get_ylim()[0]) ax.set_xlim(min_val, max_val) ax.set_ylim(min_val, max_val) # Add a diagonal line for reference (y=x) ax.plot([min_val, max_val], [min_val, max_val], 'k--', alpha=0.5, label='y=x reference') # Display the plot plt.show() In this scatter plot, we've added parameters like s for marker size, alpha for transparency (useful when points overlap), and edgecolor for better distinction. The reference line y=x helps us quickly identify genes that are expressed similarly across both conditions, and those that show differential expression.
Key Takeaways
Matplotlib is the foundational plotting library in Python for creating diverse visualizations. Understanding the Figure and Axes hierarchy is crucial for effective plot creation and customization. A Figure is the canvas, and Axes are the individual plots within it. The object-oriented interface (using fig, ax = plt.subplots() and then calling methods on ax ) provides greater control and is generally preferred. Line plots are excellent for showing trends over a continuous variable (e.g., time, concentration). Scatter plots are ideal for visualizing relationships between two quantitative variables and identifying correlations or clusters. Always include clear titles, axis labels with units, and legends to ensure your visualizations are interpretable by others.
Practice Exercise: Dose-Response Curve
Using Matplotlib, create a scatter plot to visualize a hypothetical dose-response relationship, followed by a line plot showing the trend. Generate 20 data points where the 'dose' ranges from 0 to 10 units. For the 'response', simulate a sigmoidal curve (e.g., using a logistic function) with some added random noise to mimic experimental variability. Label your axes appropriately (e.g., 'Dose (units)', 'Response (% Max)'). Add a title and a legend. For an extra challenge, try to plot both the raw scatter points and a smoothed line representing the theoretical dose-response curve on the same Axes object.
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 →