Unit 5 subjective questions Data Visualization
CAP776 — Programming In Python 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define data visualization. Explain the role of Matplotlib in Python data visualization.
Model answer
Data visualization is the graphical representation of data using plots, charts, maps, and diagrams. It helps users identify patterns, trends, relationships, and outliers that may not be apparent in raw data.
Matplotlib is a widely used Python library for creating static, animated, and interactive visualizations. Its
pyplotmodule provides functions similar to MATLAB plotting commands.Basic workflow:
- Import the module using
import matplotlib.pyplot as plt. - Prepare the data to be plotted.
- Create a plot using functions such as
plt.plot()orplt.bar(). - Add a title, axis labels, and a legend.
- Display the figure using
plt.show().
Example:
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] plt.plot(x, y) plt.xlabel("X values") plt.ylabel("Y values") plt.title("Simple Line Plot") plt.show()Matplotlib offers extensive control over figure size, colors, line styles, markers, axes, annotations, and layout.
- Import the module using
-
Question 2 of 20
Describe how to create and customize a line plot using Matplotlib. Give a suitable Python example.
Model answer
A line plot displays data points connected by straight lines. It is commonly used to represent trends over time or changes in one variable with respect to another.
The function
plt.plot(x, y)creates a line plot. It can be customized using parameters such as:color: sets the line color.linestyle: specifies styles such as solid, dashed, or dotted.linewidth: controls line thickness.marker: selects the symbol used at each data point.label: assigns a name for the legend.
Example:
import matplotlib.pyplot as plt months = [1, 2, 3, 4, 5] sales = [20, 28, 25, 35, 42] plt.plot(months, sales, color="blue", linestyle="--", linewidth=2, marker="o", label="Sales") plt.xlabel("Month") plt.ylabel("Sales in thousands") plt.title("Monthly Sales Trend") plt.grid(True) plt.legend() plt.show()The resulting plot clearly communicates the direction and magnitude of changes in sales.
-
Question 3 of 20
Explain bar charts and distinguish between vertical, horizontal, grouped, and stacked bar charts.
Model answer
A bar chart represents categorical data through rectangular bars whose lengths or heights are proportional to the corresponding values.
- Vertical bar chart: Categories are placed on the -axis, and values are measured on the -axis. It is created using
plt.bar(). - Horizontal bar chart: Categories appear on the -axis, and values are measured on the -axis. It is created using
plt.barh()and is useful for long category names. - Grouped bar chart: Bars for different series are placed side by side within each category. It is useful for comparing multiple groups directly.
- Stacked bar chart: Multiple series are placed on top of one another using the
bottomparameter. It shows both the total and the contribution of each component.
Appropriate uses:
- Comparing sales across products
- Comparing marks across subjects
- Showing departmental expenditure
- Displaying category frequencies
Unlike histograms, bar charts represent discrete categories, and gaps are usually maintained between bars.
- Vertical bar chart: Categories are placed on the -axis, and values are measured on the -axis. It is created using
-
Question 4 of 20
Write and explain a Matplotlib program that creates a grouped bar chart for two data series.
Model answer
A grouped bar chart places corresponding bars from multiple data series next to one another.
Program:
import matplotlib.pyplot as plt import numpy as np subjects = ["Python", "Java", "C++"] class_a = [80, 72, 76] class_b = [75, 78, 70] x = np.arange(len(subjects)) width = 0.35 plt.bar(x - width / 2, class_a, width=width, label="Class A") plt.bar(x + width / 2, class_b, width=width, label="Class B") plt.xticks(x, subjects) plt.xlabel("Subjects") plt.ylabel("Average marks") plt.title("Class-wise Subject Performance") plt.legend() plt.show()Explanation:
np.arange()generates numerical positions for the categories.- A width of
0.35is assigned to each bar. - Subtracting and adding positions the bars on either side of the category center.
plt.xticks()replaces numerical positions with subject names.- The legend identifies the two classes.
This chart makes comparison between the two classes easy for every subject.
-
Question 5 of 20
What is a scatter plot? Explain how it can be used to identify relationships, clusters, and outliers.
Model answer
A scatter plot represents individual observations as points in a two-dimensional coordinate system. It is created in Matplotlib using
plt.scatter(x, y).Interpretation:
- An upward pattern suggests a positive relationship: as increases, tends to increase.
- A downward pattern suggests a negative relationship: as increases, tends to decrease.
- A random distribution suggests little or no obvious relationship.
- Dense groups of points may indicate clusters or subgroups.
- Points far away from the general pattern may be outliers.
A scatter plot may be enhanced through:
- Point colors using
c - Point sizes using
s - Marker styles using
marker - Transparency using
alpha - A color scale using
plt.colorbar()
A scatter plot reveals association but does not, by itself, prove causation between variables.
-
-
Question 6 of 20
Create a scatter plot in Matplotlib in which point size and color represent additional variables. Explain the important parameters.
Model answer
A scatter plot can encode up to four dimensions through horizontal position, vertical position, point size, and point color.
Example:
import matplotlib.pyplot as plt hours = [1, 2, 3, 4, 5, 6] marks = [42, 50, 57, 65, 72, 84] attendance = [60, 65, 70, 80, 90, 95] assignments = [2, 3, 3, 4, 5, 6] plt.scatter(hours, marks, s=[a * 20 for a in assignments], c=attendance, cmap="viridis", alpha=0.75) plt.xlabel("Study hours") plt.ylabel("Marks") plt.title("Student Performance") plt.colorbar(label="Attendance percentage") plt.show()Parameter interpretation:
hourscontrols the horizontal position.markscontrols the vertical position.scontrols marker area and represents completed assignments.cmaps attendance values to colors.cmapselects the color map.alphacontrols transparency and helps when points overlap.plt.colorbar()explains the meaning of the colors.
The visualization simultaneously communicates study hours, marks, attendance, and assignments.
-
Question 7 of 20
Explain the construction, uses, and limitations of a pie chart. Mention how percentages are displayed in Matplotlib.
Model answer
A pie chart is a circular chart divided into sectors. The angle or area of each sector is proportional to its category's contribution to the total.
For a category value and total , its central angle is:
In Matplotlib, a pie chart is created with
plt.pie().Example:
import matplotlib.pyplot as plt values = [40, 30, 20, 10] labels = ["Rent", "Food", "Travel", "Other"] plt.pie(values, labels=labels, autopct="%1.1f%%", startangle=90, explode=[0.1, 0, 0, 0]) plt.title("Monthly Expenditure") plt.axis("equal") plt.show()autopct="%1.1f%%"displays percentages with one decimal place.explodeseparates a selected sector.startanglerotates the chart.
Limitations: Pie charts become difficult to interpret with many categories, similar-sized slices, negative values, or multiple datasets. A bar chart is often better for precise comparisons.
-
Question 8 of 20
Define a box-and-whisker plot. Explain its five-number summary, interquartile range, whiskers, and outliers.
Model answer
A box-and-whisker plot, or box plot, summarizes the distribution of numerical data using quartiles.
Its five-number summary consists of:
- Minimum
- First quartile
- Median
- Third quartile
- Maximum
The box extends from to , and the line inside the box represents the median. The interquartile range is:
A common rule classifies observations as potential outliers if they are below
or above
The whiskers generally extend to the smallest and largest observations lying within these limits. Values beyond the whiskers are shown individually as outliers.
Box plots help compare center, spread, skewness, and potential outliers across groups. In Matplotlib, they are created using
plt.boxplot(data). -
Question 9 of 20
Given the ordered dataset , analyze how it would be represented by a box-and-whisker plot.
Model answer
Using the median-of-halves method, the ordered data is:
Step 1: Find the median.
There are ten observations, so the median is the average of the fifth and sixth values:
Step 2: Find the quartiles.
The lower half is , so:
The upper half is , so:
Step 3: Calculate the interquartile range.
Step 4: Calculate the outlier limits.
Therefore, is a potential outlier. The lower whisker reaches , and the upper whisker reaches . The box extends from to , with the median at . Different software may use slightly different quartile conventions, but the interpretation remains similar.
-
Question 10 of 20
What is a histogram? Explain the role of bins and distinguish a histogram from a bar chart.
Model answer
A histogram represents the frequency distribution of continuous or numerical data. The data range is divided into intervals called bins, and each bar shows the number of observations falling within a bin.
In Matplotlib, a histogram is created using
plt.hist(data, bins=n).Role of bins:
- Too few bins can hide important patterns.
- Too many bins can make the distribution appear noisy.
- Appropriate bins may reveal symmetry, skewness, peaks, gaps, and unusual values.
Histogram versus bar chart:
- A histogram represents numerical intervals, whereas a bar chart represents discrete categories.
- Histogram bars normally touch because bins cover consecutive intervals; bar-chart bars usually have gaps.
- Histogram order is determined by numerical intervals; bar-chart categories may be reordered.
- Histogram width has meaning because it represents an interval; bar width in an ordinary bar chart generally has no quantitative interpretation.
- A histogram studies a distribution, while a bar chart compares category values.
Thus, selecting the chart should depend on whether the variable is numerical and continuous or categorical.
-
Question 11 of 20
Describe how a histogram can be created and customized in Matplotlib. How does
density=Trueaffect the result?Model answer
Example:
import matplotlib.pyplot as plt scores = [42, 48, 51, 55, 58, 61, 63, 65, 68, 70, 72, 75, 78, 81, 84, 86, 88, 91, 93, 96] plt.hist(scores, bins=5, color="skyblue", edgecolor="black", alpha=0.8) plt.xlabel("Score interval") plt.ylabel("Frequency") plt.title("Distribution of Scores") plt.show()Important customization options:
binsdetermines the number of intervals or specifies their boundaries.rangerestricts the interval being analyzed.colorsets bar color.edgecolormakes bin boundaries clearer.alphacontrols transparency.orientationcreates vertical or horizontal histograms.cumulative=Trueproduces cumulative values.
With the default
density=False, bar heights represent frequencies. Withdensity=True, the histogram is normalized so that the total area of all bars is :where is a bin's height and is its width. The vertical axis then represents probability density rather than raw counts.
-
Question 12 of 20
Explain how multiple subplots can be arranged in one Matplotlib figure using both
plt.subplot()andplt.subplots().Model answer
A figure is the complete drawing area, while an Axes object is an individual plotting region. Multiple Axes can be arranged in one figure to compare related visualizations.
Using
plt.subplot():import matplotlib.pyplot as plt plt.subplot(1, 2, 1) plt.plot([1, 2, 3], [2, 4, 6]) plt.title("Line Plot") plt.subplot(1, 2, 2) plt.bar(["A", "B", "C"], [4, 7, 5]) plt.title("Bar Chart") plt.tight_layout() plt.show()plt.subplot(1, 2, 1)means one row, two columns, and the first position.Using
plt.subplots():fig, axes = plt.subplots(1, 2, figsize=(10, 4)) axes[0].plot([1, 2, 3], [2, 4, 6]) axes[1].bar(["A", "B", "C"], [4, 7, 5]) fig.suptitle("Combined Figure") plt.tight_layout() plt.show()plt.subplots()is generally preferred because it provides explicit Figure and Axes objects, supporting clearer object-oriented code. -
Question 13 of 20
Design a Matplotlib figure containing four different plots in a arrangement. Explain how titles and layout are managed.
Model answer
A figure can be created with
plt.subplots(2, 2). Each Axes object is accessed by its row and column index.Program:
import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2, figsize=(10, 8)) axes[0, 0].plot([1, 2, 3], [2, 4, 3], marker="o") axes[0, 0].set_title("Line Plot") axes[0, 1].bar(["A", "B", "C"], [5, 8, 6]) axes[0, 1].set_title("Bar Chart") axes[1, 0].scatter([1, 2, 3, 4], [2, 5, 4, 8]) axes[1, 0].set_title("Scatter Plot") axes[1, 1].hist([2, 2, 3, 4, 4, 4, 5, 6], bins=5) axes[1, 1].set_title("Histogram") fig.suptitle("Data Visualization Summary", fontsize=16) plt.tight_layout(rect=[0, 0, 1, 0.95]) plt.show()Layout management:
figsizecontrols overall figure dimensions.set_title()gives each subplot an individual title.fig.suptitle()adds one main title for the complete figure.tight_layout()reduces overlap among axes, labels, and titles.- The
rectargument reserves space for the main title.
For more complex arrangements,
GridSpecorconstrained_layout=Truecan be used. -
Question 14 of 20
Introduce Seaborn and explain its major features and relationship with Matplotlib and pandas.
Model answer
Seaborn is a high-level Python visualization library designed for attractive and informative statistical graphics. It is built on top of Matplotlib and integrates closely with pandas DataFrames.
Major features:
- Attractive default themes and color palettes
- Simple syntax for statistical visualizations
- Direct use of named DataFrame columns
- Automatic legends and semantic mappings
- Convenient grouping through
hue,style, andsize - Built-in estimation and confidence-interval support
- Functions for categorical, relational, distributional, and matrix plots
- Faceting through functions such as
relplot()andcatplot()
Relationship with other libraries:
- Matplotlib provides the underlying plotting infrastructure and detailed customization.
- pandas supplies tabular data, with columns mapped to plot variables.
- Seaborn simplifies common statistical plotting tasks while returning Matplotlib objects that can be customized further.
Typical import:
import seaborn as sns import matplotlib.pyplot as pltA theme may be applied with
sns.set_theme(style="whitegrid"). Therefore, Seaborn complements rather than completely replaces Matplotlib. -
Question 15 of 20
Compare Seaborn and Matplotlib with respect to abstraction, customization, statistical plotting, DataFrame support, and suitable use cases.
Model answer
Matplotlib and Seaborn comparison:
- Abstraction: Matplotlib is relatively low-level and gives explicit control over plot elements. Seaborn provides higher-level functions requiring less code for many statistical charts.
- Customization: Matplotlib offers very detailed customization of artists, axes, ticks, labels, and layouts. Seaborn has attractive defaults but relies on Matplotlib for fine-grained modifications.
- Statistical plotting: Matplotlib primarily draws specified values. Seaborn can perform operations such as aggregation, regression fitting, and confidence-interval estimation.
- DataFrame support: Matplotlib can use DataFrame data, but users often pass arrays explicitly. Seaborn naturally accepts a DataFrame through
dataand refers to columns by name. - Themes and palettes: Seaborn provides coordinated themes and statistically useful color palettes. Matplotlib also supports styles but generally requires more manual configuration.
- Complex layouts: Matplotlib provides comprehensive figure and subplot control. Seaborn supports figure-level faceting, while complex custom arrangements may still require Matplotlib.
Suitable use cases:
- Use Matplotlib for fully customized, publication-specific, or unusual plots.
- Use Seaborn for rapid exploratory analysis and statistical visualization.
- In practice, use Seaborn to create a plot and Matplotlib to refine it.
-
Question 16 of 20
Explain Seaborn's axes-level and figure-level functions. Give examples and state when each should be used.
Model answer
Seaborn functions can broadly be classified as axes-level or figure-level.
Axes-level functions draw on a single Matplotlib Axes object. Examples include:
sns.scatterplot()sns.lineplot()sns.barplot()sns.histplot()sns.boxplot()sns.heatmap()
They accept an
axparameter and are easy to place inside custom Matplotlib subplot layouts.fig, ax = plt.subplots() sns.scatterplot(data=df, x="hours", y="marks", ax=ax)Figure-level functions manage an entire figure and can generate several subplots through faceting. Examples include:
sns.relplot()sns.catplot()sns.displot()-
sns.lmplot()sns.relplot(data=df, x="hours", y="marks",
col="class", hue="gender")
Figure-level functions usually return objects such as
FacetGrid, rather than a single Axes.Selection:
- Use axes-level functions when integrating a Seaborn chart into a manually controlled Matplotlib figure.
- Use figure-level functions when automatic faceting across categories is required.
Understanding this distinction avoids layout conflicts and supports better plot organization.
-
Question 17 of 20
Describe how relational and categorical data can be visualized using Seaborn. Include suitable code examples.
Model answer
Seaborn provides specialized functions for relational and categorical data.
Relational visualization:
import seaborn as sns import matplotlib.pyplot as plt sns.scatterplot(data=df, x="study_hours", y="marks", hue="class", style="gender", size="attendance") plt.show()In this example:
xandydefine the relationship.huemaps class values to colors.stylemaps gender to marker shapes.sizemaps attendance to marker sizes.
sns.lineplot()may be used when data has an ordered progression, such as time.Categorical visualization:
sns.barplot(data=df, x="department", y="salary", hue="gender") plt.show()By default,
barplot()estimates a summary statistic, commonly the mean, for every category and can display uncertainty intervals depending on the Seaborn version and parameters.Other categorical functions include:
countplot()for category countsboxplot()for distribution summariesviolinplot()for distribution shape and quartilesstripplot()for individual observationsswarmplot()for non-overlapping observations
The plot type should be selected according to whether the goal is to show counts, summaries, complete distributions, or individual data points.
-
Question 18 of 20
Explain distribution visualization in Seaborn using histograms, kernel density estimates, box plots, and violin plots.
Model answer
Seaborn provides several complementary ways to study distributions.
- Histogram:
sns.histplot()divides numerical data into bins and displays frequency or density. It is useful for observing peaks, skewness, and spread. - Kernel density estimate:
sns.kdeplot()creates a smooth estimate of the probability density. Its appearance depends on bandwidth, so excessive smoothing may hide details and insufficient smoothing may introduce noise. - Box plot:
sns.boxplot()summarizes a distribution using quartiles, median, whiskers, and potential outliers. It is especially useful for comparing groups. - Violin plot:
sns.violinplot()combines a box-plot-style summary with a mirrored density shape, showing where values are concentrated.
Example:
import seaborn as sns import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 3, figsize=(15, 4)) sns.histplot(data=df, x="score", kde=True, ax=axes[0]) sns.boxplot(data=df, x="class", y="score", ax=axes[1]) sns.violinplot(data=df, x="class", y="score", ax=axes[2]) plt.tight_layout() plt.show()Using multiple distribution plots provides a more complete understanding than relying on a single chart.
- Histogram:
-
Question 19 of 20
What principles should be followed to produce clear, accurate, and accessible data visualizations?
Model answer
Effective data visualization requires both technical correctness and thoughtful design.
Important principles:
- Select a chart that matches the data type and analytical purpose.
- Provide a meaningful title and clearly label axes with units.
- Use readable scales and avoid unnecessary axis truncation that exaggerates differences.
- Keep the design simple and remove nonessential decoration.
- Use color consistently and choose color-blind-friendly palettes.
- Avoid using too many colors, categories, or labels in one plot.
- Provide a legend when visual encodings are not self-explanatory.
- Use annotations to emphasize important findings without cluttering the figure.
- Represent uncertainty when displaying estimated values.
- Avoid three-dimensional effects when they distort perceived values.
- Ensure text, lines, and markers remain readable at the intended output size.
- Include data sources and relevant context when presenting results.
Accessibility may be improved by combining color with marker shape, line style, or direct labels so that meaning does not depend on color alone. A good visualization should communicate its main message accurately and quickly.
-
Question 20 of 20
What is a data dashboard? Describe important Python tools for creating dashboards and compare their main characteristics.
Model answer
A data dashboard is an interactive visual interface that presents key metrics, charts, filters, and summaries in a unified layout. Dashboards help users monitor performance, explore data, and support decisions.
Important Python-related dashboard tools:
- Streamlit: Converts Python scripts into web applications with minimal code. It is suitable for rapid prototypes, machine-learning demonstrations, and internal data applications.
- Plotly Dash: A framework based on Plotly, Flask, and component-based web interfaces. It provides detailed control over interactive charts, callbacks, and application behavior.
- Bokeh: Supports interactive browser visualizations and server applications. It is effective for streaming or frequently updated data.
- Panel: Part of the HoloViz ecosystem. It can combine plots, widgets, tables, and objects from multiple visualization libraries.
- Voilà: Converts Jupyter notebooks into standalone dashboard-style web applications while hiding notebook code cells.
- Tableau and Microsoft Power BI: Primarily graphical business-intelligence tools rather than Python libraries. They support drag-and-drop dashboard design, data connections, filtering, sharing, and organizational reporting.
Typical dashboard elements:
- Key performance indicators
- Interactive charts and tables
- Date, category, and range filters
- Tooltips and drill-down controls
- Responsive layout
- Data refresh mechanisms
Tool selection depends on programming skill, deployment requirements, interactivity, data volume, cost, governance, and intended users.
That's unit 5
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 5 of CAP776 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 5 of CAP776 save you a night before the exam?
Then you can help keep it free for the next batch. 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.