Unit 11: Data visualization - Subjective Questions
ECAP776 • Practice Questions with Detailed Answers
20 questions
Define data visualization. Explain the purpose and major features of the Matplotlib library in Python.
Data visualization is the graphical representation of data using plots, charts, and diagrams. It helps users identify patterns, trends, relationships, and unusual observations.
Matplotlib is a Python library used to create static, animated, and interactive visualizations.
Major features:
- Supports line plots, bar charts, histograms, scatter plots, box plots, and pie charts.
- Provides control over colors, labels, markers, line styles, and axes.
- Can display multiple plots in one figure.
- Integrates well with NumPy and pandas.
- Allows figures to be saved in formats such as PNG, PDF, and SVG.
It is commonly imported as import matplotlib.pyplot as plt.
Describe the basic steps required to create and display a plot using matplotlib.pyplot.
The basic plotting procedure is:
- Import the module:
import matplotlib.pyplot as plt - Prepare data: Store values in lists, NumPy arrays, or pandas objects.
- Create the plot: Call a function such as
plt.plot(x, y). - Add descriptions: Use
plt.title(),plt.xlabel(), andplt.ylabel(). - Add optional features: Use
plt.legend()andplt.grid(). - Display the figure: Call
plt.show().
Example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()
Matplotlib joins corresponding coordinate pairs to form the displayed line.
What is a line plot? Explain how to create one in Matplotlib and state the situations in which it is useful.
A line plot represents data points connected by straight line segments. It is especially useful for displaying changes over an ordered sequence, such as time.
Example:
days = [1, 2, 3, 4, 5]
temperature = [28, 30, 29, 32, 34]
plt.plot(days, temperature)
plt.xlabel("Day")
plt.ylabel("Temperature")
plt.title("Daily Temperature")
plt.show()
Uses of a line plot:
- Showing trends over time
- Comparing consecutive measurements
- Identifying increases, decreases, and fluctuations
- Comparing multiple related series
The horizontal axis normally represents the ordered independent variable, while the vertical axis represents the measured value.
Explain how colors, markers, line styles, labels, legends, and grids can be used to customize a line plot.
A line plot can be customized through arguments to plot() and other Pyplot functions.
plt.plot(x, y, color="blue", marker="o", linestyle="--", label="Sales")
plt.xlabel("Month")
plt.ylabel("Units")
plt.title("Monthly Sales")
plt.legend()
plt.grid(True)
Customization elements:
colorcontrols the line color.markeridentifies each data point, such aso,s, or^.linestylemay be solid, dashed, dotted, or dash-dot.labelassigns a name to the series.plt.legend()displays series labels.plt.grid(True)adds reference lines for easier reading.linewidthandmarkersizecontrol visual emphasis.
These features improve readability, but excessive decoration should be avoided.
How can multiple data series be drawn on the same line plot? Explain with a suitable example and discuss the role of a legend.
Multiple series can be drawn by calling plt.plot() once for each series before calling plt.show().
years = [2022, 2023, 2024, 2025]
product_a = [40, 55, 60, 72]
product_b = [35, 48, 65, 68]
plt.plot(years, product_a, marker="o", label="Product A")
plt.plot(years, product_b, marker="s", label="Product B")
plt.xlabel("Year")
plt.ylabel("Sales")
plt.title("Product Sales Comparison")
plt.legend()
plt.show()
Each call adds a line to the same axes. The legend maps each color or style to its series name, allowing viewers to distinguish the lines. Clearly different colors, markers, or line styles should be selected.
What are subplots? Explain how plt.subplots() can be used to create multiple plots in one figure.
Subplots are separate plotting areas, called axes, arranged inside one figure. They make it possible to compare related visualizations without opening separate windows.
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes[0, 0].plot(x, y1)
axes[0, 1].bar(categories, values)
axes[1, 0].hist(data)
axes[1, 1].scatter(x, y2)
plt.tight_layout()
plt.show()
In this example:
figrepresents the complete figure.axesis a two-dimensional collection of four plotting areas.axes[row, column]selects a particular subplot.figsizecontrols the overall figure dimensions.tight_layout()reduces label and title overlap.
Each axes object can have its own title, labels, and plotting method.
Describe how to organize and improve multiple subplots using shared axes, subplot titles, a figure title, figure size, and automatic layout adjustment.
Matplotlib provides several options for organizing subplots:
fig, axes = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
axes[0].plot(x, y1)
axes[0].set_title("First Series")
axes[1].plot(x, y2)
axes[1].set_title("Second Series")
axes[1].set_xlabel("Time")
fig.suptitle("Performance Report")
fig.tight_layout()
Important options:
sharex=Trueorsharey=Truegives subplots a common axis scale.set_title()assigns an individual subplot title.suptitle()assigns a title to the complete figure.figsize=(width, height)specifies size in inches.tight_layout()adjusts spacing automatically.subplots_adjust()can manually control margins and spacing.
Shared scales support fair comparison and reduce repeated axis labels.
Define a bar chart. Explain how vertical and horizontal bar charts are created and identify appropriate applications.
A bar chart represents values using rectangular bars whose lengths or heights are proportional to the values. It is suitable for comparing discrete categories.
Vertical bar chart:
plt.bar(categories, values, color="steelblue")
Horizontal bar chart:
plt.barh(categories, values, color="orange")
Labels and a title can be added with xlabel(), ylabel(), and title().
Appropriate applications:
- Comparing sales of different products
- Displaying student counts by course
- Comparing frequencies of categories
- Ranking a small number of items
Horizontal bars are particularly useful when category names are long. A bar chart should normally use a zero baseline so that bar lengths do not give a misleading comparison.
Distinguish between simple, grouped, and stacked bar charts. Describe how grouped and stacked bar charts can be constructed in Matplotlib.
Simple bar chart: Shows one value for each category.
Grouped bar chart: Places bars for different series side by side, making individual series easy to compare.
Stacked bar chart: Places one series on top of another, showing both the total and each component's contribution.
For a grouped chart, bar positions are shifted by a width :
import numpy as np
x = np.arange(len(categories))
w = 0.35
plt.bar(x - w/2, values_a, width=w, label="A")
plt.bar(x + w/2, values_b, width=w, label="B")
plt.xticks(x, categories)
plt.legend()
For a stacked chart:
plt.bar(categories, values_a, label="A")
plt.bar(categories, values_b, bottom=values_a, label="B")
Grouped charts emphasize comparison, whereas stacked charts emphasize totals and composition.
What is a histogram? Explain how it differs from a bar chart and how it is created using Matplotlib.
A histogram displays the frequency distribution of continuous numerical data. It divides a range into intervals called bins and counts how many observations fall into each interval.
scores = [52, 61, 67, 67, 70, 72, 78, 81, 85, 91]
plt.hist(scores, bins=5, edgecolor="black")
plt.xlabel("Score Interval")
plt.ylabel("Frequency")
plt.title("Score Distribution")
plt.show()
Histogram versus bar chart:
- A histogram represents continuous numerical intervals; a bar chart represents discrete categories.
- Histogram bars normally touch because bins are continuous.
- Bar-chart bars normally have gaps between categories.
- Histogram order is numerical and fixed; bar categories can often be reordered.
- Histogram width represents an interval, while bar width usually has no numerical meaning.
Explain the importance of bin selection in a histogram. What happens when too few or too many bins are used?
A bin is an interval used to group observations in a histogram. Bin selection strongly affects the apparent shape of the distribution.
- Too few bins: The graph becomes over-smoothed. Peaks, gaps, and clusters may be hidden.
- Too many bins: The graph becomes noisy. Random fluctuations may appear to be meaningful patterns.
- Suitable bins: Reveal the distribution's center, spread, skewness, and possible modes without unnecessary noise.
Bins may be specified as a count or as explicit boundaries:
plt.hist(data, bins=10)
plt.hist(data, bins=[0, 10, 20, 30, 40, 50])
Different reasonable bin widths should be examined. When comparing groups, common bin boundaries and axis scales should be used so that visual differences are meaningful.
Describe a box and whisker plot. Explain its five-number summary, interquartile range, whiskers, and outliers.
A box and whisker plot, or box plot, summarizes the location and spread of numerical data.
Its five-number summary consists of:
- Minimum
- First quartile
- Median
- Third quartile
- Maximum
The box extends from to , and the line inside it marks the median. The interquartile range is:
Under the common convention, observations below or above are plotted as potential outliers. Whiskers extend to the most extreme non-outlier observations.
A box plot can be created with plt.boxplot(data). It compactly reveals center, spread, skewness, and unusual values.
Compare histograms and box plots as methods of studying a numerical distribution.
Both charts summarize numerical data, but they emphasize different properties.
Histogram:
- Displays frequencies across intervals.
- Reveals distribution shape, peaks, gaps, and multiple modes.
- Depends on the selected bins.
- Usually requires more plotting space.
Box plot:
- Displays quartiles, median, spread, and potential outliers.
- Does not reveal detailed distribution shape or multiple peaks.
- Is compact and useful for comparing several groups.
- Does not depend on histogram bins.
A histogram is preferable when the detailed shape of one distribution is important. Side-by-side box plots are preferable when comparing the center, variability, and outliers of multiple groups. Using both can provide a more complete understanding.
What is a scatter plot? Explain how it helps investigate the relationship between two numerical variables.
A scatter plot represents each observation as a point with coordinates , where and are values of two numerical variables.
hours = [1, 2, 3, 4, 5, 6]
scores = [45, 50, 58, 65, 72, 80]
plt.scatter(hours, scores)
plt.xlabel("Study Hours")
plt.ylabel("Score")
plt.title("Study Hours and Scores")
plt.show()
It can reveal:
- Positive association: generally increases as increases.
- Negative association: generally decreases as increases.
- No clear association: Points show no consistent direction.
- Clusters, curved relationships, changing spread, and outliers.
A visible association does not by itself prove that one variable causes the other.
Explain how marker color, size, shape, transparency, and a color bar can add information to a scatter plot.
Scatter-plot markers can encode additional variables and improve the visibility of overlapping observations.
plot = plt.scatter(x, y, c=group_value, s=marker_size,
cmap="viridis", alpha=0.6, marker="o")
plt.colorbar(plot, label="Group Value")
Parameters:
cassigns colors, possibly according to a third variable.scontrols marker area and can represent magnitude.markerchanges marker shape.alphacontrols transparency; lower values help reveal overlapping points.cmapchooses a color map for numerical color values.colorbar()explains how colors correspond to values.
Encodings must be accompanied by labels or legends. Marker size and color should not be overloaded because too many visual variables can make the chart difficult to interpret.
Define a pie chart. Explain how to create and customize one using labels, percentages, colors, start angle, and exploded slices.
A pie chart is a circular chart divided into slices that represent proportions of a whole. The values should be non-negative and should describe mutually exclusive parts of one total.
values = [40, 30, 20, 10]
labels = ["A", "B", "C", "D"]
explode = [0.1, 0, 0, 0]
plt.pie(values, labels=labels, autopct="%1.1f%%",
startangle=90, explode=explode,
colors=["gold", "skyblue", "lightgreen", "pink"])
plt.axis("equal")
plt.title("Market Share")
plt.show()
labelsnames the slices.autopctprints percentages.colorssets slice colors.startanglerotates the chart.explodeseparates selected slices.axis("equal")keeps the pie circular.
Discuss the advantages and limitations of pie charts. When should a bar chart be preferred?
Advantages of pie charts:
- Present part-to-whole relationships directly.
- Are familiar and visually simple for a few categories.
- Can highlight a dominant category.
Limitations:
- Similar angles and areas are difficult to compare accurately.
- Many slices create clutter and unreadable labels.
- Small differences between categories are hard to detect.
- Negative values and unrelated totals are inappropriate.
- Multiple pie charts are difficult to compare consistently.
- Three-dimensional effects may distort apparent proportions.
A bar chart should be preferred when there are many categories, category values are close, exact comparison matters, or several groups must be compared. Pie charts are most effective with a small number of clearly different slices that together represent one meaningful whole.
Distinguish among line plots, bar charts, histograms, box plots, scatter plots, and pie charts based on the type of data and analytical purpose.
Chart selection should match the data and the intended message:
- Line plot: Shows change or trend across an ordered variable, especially time.
- Bar chart: Compares quantities across discrete categories.
- Histogram: Shows the frequency distribution of one continuous numerical variable.
- Box plot: Summarizes median, quartiles, variability, and potential outliers; useful for group comparisons.
- Scatter plot: Investigates the relationship between two numerical variables.
- Pie chart: Shows how a small number of categories contribute to one total.
For example, monthly temperature is suited to a line plot, product sales to a bar chart, examination-score distribution to a histogram, salaries across departments to box plots, height versus weight to a scatter plot, and a simple budget composition to a pie chart. Selecting the wrong chart can conceal patterns or mislead viewers.
Design a Matplotlib figure containing four subplots to visualize monthly sales as a line plot, regional sales as a bar chart, customer ages as a histogram, and advertising cost versus revenue as a scatter plot. Explain the main steps.
A subplot arrangement can display all four views:
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
axes[0, 0].plot(months, monthly_sales, marker="o")
axes[0, 0].set_title("Monthly Sales")
axes[0, 0].set_xlabel("Month")
axes[0, 0].set_ylabel("Sales")
axes[0, 1].bar(regions, regional_sales)
axes[0, 1].set_title("Regional Sales")
axes[1, 0].hist(customer_ages, bins=10, edgecolor="black")
axes[1, 0].set_title("Customer Age Distribution")
axes[1, 1].scatter(ad_cost, revenue, alpha=0.7)
axes[1, 1].set_title("Advertising Cost vs Revenue")
axes[1, 1].set_xlabel("Advertising Cost")
axes[1, 1].set_ylabel("Revenue")
fig.suptitle("Sales Analysis Dashboard")
fig.tight_layout()
plt.show()
The data must first be cleaned and aligned. Each chart receives suitable labels, while consistent colors, units, and scales make the dashboard easier to interpret.
Explain good practices for creating clear and non-misleading Matplotlib visualizations, including labeling, scales, colors, layout, and saving figures.
Good visualization practices include:
- Select a chart appropriate for the variable types and analytical goal.
- Provide an informative title and clearly label both axes with units.
- Use readable fonts, markers, and line widths.
- Add legends only when multiple series or encodings require explanation.
- Use consistent scales when comparing plots.
- Normally start bar-chart value axes at zero to avoid exaggerating differences.
- Choose accessible, high-contrast colors and avoid unnecessary effects.
- Limit clutter, excessive grid lines, and decorative three-dimensional styling.
- Use
tight_layout()to prevent overlapping labels. - Check missing values, unequal array lengths, and incorrect data types.
-
Save output with an appropriate resolution:
plt.savefig("figure.png", dpi=300, bbox_inches="tight")
savefig() should normally be called before show() in environments where displaying the figure may clear or close it.
Define data visualization. Explain the purpose and major features of the Matplotlib library in Python.
Data visualization is the graphical representation of data using plots, charts, and diagrams. It helps users identify patterns, trends, relationships, and unusual observations.
Matplotlib is a Python library used to create static, animated, and interactive visualizations.
Major features:
- Supports line plots, bar charts, histograms, scatter plots, box plots, and pie charts.
- Provides control over colors, labels, markers, line styles, and axes.
- Can display multiple plots in one figure.
- Integrates well with NumPy and pandas.
- Allows figures to be saved in formats such as PNG, PDF, and SVG.
It is commonly imported as import matplotlib.pyplot as plt.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →