Lesson · 40 min · Free
Matplotlib Data Visualization
Matplotlib Data Visualization Matplotlib Data Visualization In the realm of pharmacy and biotechnology, data visualization is an indispensable tool for understanding complex datasets, communicating findings, and making i
Matplotlib Data Visualization
In the realm of pharmacy and biotechnology, data visualization is an indispensable tool for understanding complex datasets, communicating findings, and making informed decisions. From analyzing drug efficacy in clinical trials to visualizing gene expression patterns, the ability to present data clearly and effectively is paramount. Matplotlib, a foundational plotting library in Python, provides a robust and flexible framework for creating a wide array of static, animated, and interactive visualizations. While more specialized libraries like Seaborn build upon Matplotlib for statistical plotting, a solid understanding of Matplotlib's core functionalities is crucial for customizing plots and achieving precise control over your visualizations. Matplotlib's architecture is built around several key components: the Figure, Axes, and various plot elements. The Figure is the top-level container for all plot elements. Think of it as the canvas on which you will draw. An Axes object (note the plural 's', not 'axis') is the region of the image with the data space. A single Figure can contain multiple Axes, allowing for subplots or multiple visualizations within one image. Within an Axes, you can then add various plot elements like lines, scatter points, bars, text, and labels. Understanding this hierarchy is fundamental to effectively manipulating your plots. Let's start with a basic example: creating a simple line plot. We often encounter time-series data in pharmacy, such as drug concentration over time. Matplotlib allows us to visualize this effectively. import matplotlib.pyplot as plt import numpy as np # Simulate drug concentration over time time_points = np.linspace(0, 24, 50) # 0 to 24 hours initial_dose = 100 # mg elimination_rate = 0.15 # per hour concentration = initial_dose * np.exp(-elimination_rate * time_points) # Create the plot plt.figure(figsize=(10, 6)) # Set figure size for better readability plt.plot(time_points, concentration, marker='o', linestyle='-', color='blue', label='Drug Concentration') # Add labels and title for clarity plt.title('Simulated Drug Concentration Over Time', fontsize=16) plt.xlabel('Time (hours)', fontsize=12) plt.ylabel('Concentration (mg/L)', fontsize=12) plt.grid(True, linestyle='--', alpha=0.7) # Add a grid for easier reading plt.legend() # Display the label plt.show() # Display the plot This code snippet demonstrates the creation of a Figure and Axes implicitly through plt.plot() and then explicitly adds a title, labels, and a legend. The marker='o' adds circles at each data point, and linestyle='-' connects them with a solid line. The plt.show() function is essential to render the plot. Without it, the plot might not appear, especially in non-interactive environments. Beyond line plots, scatter plots are incredibly useful for visualizing the relationship between two variables, such as the correlation between drug dose and patient response. Histograms, on the other hand, help us understand the distribution of a single variable, which is crucial for analyzing clinical trial data or patient demographics. Bar charts are excellent for comparing discrete categories, like the efficacy of different treatment groups. Let's explore a more complex scenario involving subplots, which allow us to display multiple plots within a single figure. This is particularly useful when comparing different aspects of a dataset side-by-side. import matplotlib.pyplot as plt import numpy as np import pandas as pd # Simulate patient data for two treatment groups np.random.seed(42) # for reproducibility # Group A: Placebo placebo_response = np.random.normal(loc=5, scale=2, size=100) # e.g., pain reduction score # Group B: Treatment treatment_response = np.random.normal(loc=12, scale=3, size=100) # Create a figure with two subplots (1 row, 2 columns) fig, axes = plt.subplots(1, 2, figsize=(14, 6)) # fig is the Figure, axes is an array of Axes objects # Subplot 1: Histograms of patient response axes[0].hist(placebo_response, bins=15, alpha=0.7, color='lightcoral', label='Placebo') axes[0].hist(treatment_response, bins=15, alpha=0.7, color='lightseagreen', label='Treatment') axes[0].set_title('Distribution of Patient Response', fontsize=14) axes[0].set_xlabel('Response Score', fontsize=12) axes[0].set_ylabel('Frequency', fontsize=12) axes[0].legend() axes[0].grid(axis='y', linestyle='--', alpha=0.7) # Subplot 2: Box plots for comparison data_to_plot = [placebo_response, treatment_response] axes[1].boxplot(data_to_plot, patch_artist=True, boxprops=dict(facecolor='lightblue', edgecolor='black'), medianprops=dict(color='red')) axes[1].set_title('Comparison of Response Groups', fontsize=14) axes[1].set_ylabel('Response Score', fontsize=12) axes[1].set_xticks([1, 2]) axes[1].set_xticklabels(['Placebo', 'Treatment']) axes[1].grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout() # Adjust subplot parameters for a tight layout plt.suptitle('Clinical Trial Data Analysis', fontsize=18, y=1.03) # Overall title for the figure plt.show() In this second example, plt.subplots(1, 2, ...) creates a figure and an array of two Axes objects. We then access these individual Axes using indexing ( axes[0] and axes[1] ) to plot histograms and box plots respectively. Notice how methods like set_title() , set_xlabel() , and set_ylabel() are used on the individual Axes objects, rather than the global plt.title() , etc. This is crucial when working with multiple subplots. plt.tight_layout() automatically adjusts subplot parameters for a tight layout, preventing labels from overlapping.
Key Takeaways
Matplotlib is a fundamental Python library for creating static, animated, and interactive visualizations. The core components are the Figure (the canvas) and Axes (the plotting region). matplotlib.pyplot (imported as plt ) provides a convenient interface for creating plots. Common plot types include line plots, scatter plots, histograms, and box plots, each suited for different data analysis tasks. Subplots (using plt.subplots() ) allow you to display multiple plots within a single figure for comparative analysis. Always include plt.show() to display your plots. Customize plots using methods like plt.title() , plt.xlabel() , plt.ylabel() , plt.legend() , and specific plot function arguments (e.g., color , marker , linestyle ).
Practice Exercise: Gene Expression Analysis
Imagine you are analyzing gene expression data from two different cell lines, 'Control' and 'Treated', for a specific gene. You have collected expression levels (arbitrary units) for 50 samples in each group. Your task is to: Generate synthetic data for 'Control' (e.g., a normal distribution with mean 10, std dev 2) and 'Treated' (e.g., a normal distribution with mean 15, std dev 3). Create a Matplotlib figure with two subplots: The first subplot should be a histogram comparing the distribution of gene expression for 'Control' and 'Treated' groups. Ensure different colors and alpha values for transparency. The second subplot should be a violin plot (a combination of box plot and kernel density estimate) to visualize the distribution and density of gene expression for both groups. Add appropriate titles, x-labels, y-labels, and legends to all plots. Add an overall title to the entire figure. Ensure the layout is tight and readable. This exercise will reinforce your understanding of creating subplots, using different plot types, and customizing your visualizations for scientific communication.
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 →