Unit 12: Data visualization - Subjective Questions
ECAP776 • Practice Questions with Detailed Answers
20 questions
Define Seaborn and explain its role in Python data visualization.
Seaborn is a high-level Python library used to create attractive and informative statistical graphics. It is built on top of Matplotlib and integrates closely with pandas data structures.
Its main roles are:
- Providing simple functions for complex statistical visualizations.
- Applying attractive default themes and color palettes.
- Supporting DataFrames through column-name-based plotting.
- Visualizing relationships, distributions, and categorical data.
- Performing operations such as statistical aggregation and confidence-interval estimation automatically.
For example, sns.scatterplot(data=df, x="height", y="weight") creates a scatter plot directly from DataFrame columns.
Describe the steps required to install, import, and begin using Seaborn.
The basic steps are:
- Install Seaborn: Run
pip install seabornin a terminal. - Import Seaborn: Use
import seaborn as sns. - Import Matplotlib: Use
import matplotlib.pyplot as pltbecause Matplotlib controls final rendering and customization. - Load or create data: A dataset may be represented by a pandas DataFrame.
- Create a plot: Call a function such as
sns.lineplot(data=df, x="day", y="sales"). - Display the plot: Use
plt.show().
A built-in sample dataset can be loaded with df = sns.load_dataset("tips"). This function normally downloads the dataset and therefore may require network access if it is not cached.
Compare Seaborn and Matplotlib with respect to abstraction, appearance, data handling, and customization.
Seaborn and Matplotlib serve complementary purposes.
| Basis | Seaborn | Matplotlib |
|---|---|---|
| Abstraction | High-level statistical interface | Low-level, general-purpose plotting interface |
| Appearance | Attractive themes and palettes by default | Basic defaults with detailed manual control |
| Data handling | Works naturally with pandas DataFrames and named columns | Commonly accepts arrays or explicit sequences |
| Statistical features | Can perform aggregation, grouping, and uncertainty estimation | Such calculations are usually prepared manually |
| Customization | Convenient but comparatively abstract | Fine-grained control over nearly every plot element |
| Best use | Rapid statistical exploration | Highly customized or specialized figures |
Seaborn is built on Matplotlib, so a Seaborn chart can still be modified using methods such as ax.set_title() and plt.tight_layout().
Explain how pandas DataFrames and tidy data support visualization in Seaborn.
Seaborn is designed to work effectively with tidy or long-form data. In tidy data:
- Each row represents one observation.
- Each column represents one variable.
- Each cell contains one value.
When a DataFrame is supplied through data, column names can be assigned to visual roles. For example, sns.scatterplot(data=df, x="age", y="income", hue="region") maps age to the horizontal axis, income to the vertical axis, and region to color.
This approach improves readability because users do not need to extract individual arrays. It also enables Seaborn to group observations, create legends, calculate estimates, and handle semantic mappings automatically.
Distinguish between axes-level and figure-level functions in Seaborn, giving suitable examples.
Axes-level functions draw one plot on a Matplotlib Axes object. Examples include scatterplot(), lineplot(), boxplot(), and histplot(). They can receive an existing axes through the ax parameter and are convenient when building custom Matplotlib subplots.
Figure-level functions manage an entire figure and can create multiple subplots through faceting. Examples include:
relplot()for relational plots.displot()for distribution plots.catplot()for categorical plots.lmplot()for regression plots.
Figure-level functions usually return grid objects such as FacetGrid, while axes-level functions return a Matplotlib Axes. Therefore, ax.set_title() is suitable for an axes-level result, whereas figure-level results may be customized through methods such as g.set_axis_labels() and g.figure.suptitle().
Explain the purpose of Seaborn themes and describe how plot style and context can be configured.
A Seaborn theme controls the overall visual appearance of plots. It can affect the background, grid lines, fonts, line widths, and plotting context.
sns.set_theme()applies Seaborn's default theme.- The
styleparameter supports options such as"darkgrid","whitegrid","dark","white", and"ticks". - The
contextparameter supports"paper","notebook","talk", and"poster", which scale visual elements for different presentation settings. sns.despine()can remove selected plot borders.
For example, sns.set_theme(style="whitegrid", context="talk") produces a light grid and enlarges elements for a presentation. A temporary theme can be applied using a context manager such as with sns.axes_style("ticks"):.
Describe Seaborn color palettes and explain how an appropriate palette should be selected for different data types.
A color palette is a collection or mapping of colors used to represent data values or categories.
- Qualitative palettes use distinct colors for unordered categories. Examples include
"deep","muted", and"colorblind". - Sequential palettes vary gradually from light to dark and are suitable for ordered numeric values. Examples include
"Blues"and"viridis". - Diverging palettes use two contrasting directions around a meaningful midpoint, such as zero. Examples include
"vlag"and"coolwarm".
Palettes can be inspected with sns.color_palette() and applied globally with sns.set_palette(). Selection should consider the variable's meaning, sufficient contrast, accessibility, and whether the chart will be printed. Color should not be the only indicator when viewers may have color-vision deficiencies.
Explain how scatterplot() can visualize relationships among multiple variables in a dataset.
sns.scatterplot() displays the relationship between two numeric variables by representing every observation as a point.
Its major semantic mappings include:
xandyfor position.huefor color.stylefor marker shape.sizefor marker size.
For example, sns.scatterplot(data=df, x="bill", y="tip", hue="day", style="smoker", size="party_size") can display five variables simultaneously. The resulting graph may reveal association, clusters, unusual observations, and differences among groups.
However, too many mappings may make the graph difficult to interpret. Transparency through alpha, sensible marker sizes, clear labels, and a limited number of categories improve readability.
Describe the use of lineplot() and explain how it handles repeated observations and uncertainty.
sns.lineplot() is used to show change, trend, or relationship along an ordered variable such as time. A basic example is sns.lineplot(data=df, x="month", y="sales").
When multiple observations share the same value, Seaborn commonly:
- Groups observations by and any semantic variables.
- Computes an estimator, normally the arithmetic mean.
- Draws the estimated line.
- Displays an uncertainty band according to the selected error-bar setting.
The mean for a group of observations is
Options such as estimator=None can display observations without aggregation, while errorbar=None suppresses the uncertainty interval. The hue and style parameters can distinguish multiple series.
Explain how histograms and kernel density estimates are used to study data distributions in Seaborn.
A histogram divides a numeric range into intervals called bins and represents the number or proportion of observations in each interval. It can be created with sns.histplot(data=df, x="value", bins=20).
A kernel density estimate (KDE) produces a smooth estimate of the probability density and can be created with sns.kdeplot(data=df, x="value") or by setting kde=True in histplot().
These plots help identify:
- Central tendency and spread.
- Skewness and multiple modes.
- Gaps and possible outliers.
- Differences between groups through
hue.
Histogram appearance depends strongly on bin width, while KDE appearance depends on bandwidth. Excessive smoothing can hide structure, and insufficient smoothing can produce misleading fluctuations. KDE is less suitable for very small or strongly discrete datasets.
Differentiate among box plots, violin plots, and strip plots for visualizing categorical data.
These plots compare a numeric variable across categories but emphasize different information.
- A box plot, created with
sns.boxplot(), summarizes the median, quartiles, interquartile range, whiskers, and possible outliers. The interquartile range is . - A violin plot, created with
sns.violinplot(), combines distribution density with summary information. It reveals shape and multiple modes but may be less intuitive for small samples. - A strip plot, created with
sns.stripplot(), displays individual observations. Jitter can reduce overlap, but dense datasets may suffer from overplotting.
A box or violin plot can be combined with a strip plot to show both summary and individual values. The choice depends on sample size and whether the goal is to emphasize summary statistics, distribution shape, or raw observations.
Describe the purpose of count plots, bar plots, and point plots in Seaborn.
The three plots serve different categorical-analysis purposes:
sns.countplot()displays the number of observations in each category. It is appropriate for category frequencies and generally requires no numeric response variable.sns.barplot()displays an estimated value, commonly the mean of a numeric variable, for every category. It may also show uncertainty using error bars.sns.pointplot()displays estimates as points and can connect them with lines, making changes and interactions across categories easier to compare.
A count plot answers how many observations are present, whereas a bar plot answers what is the estimated numeric value for each group. A point plot is especially useful when relative differences and trends matter more than filled rectangular areas.
Explain how relplot(), catplot(), and displot() support faceted data visualization.
These are figure-level functions that combine a plotting family with faceting:
relplot()creates relational plots such as scatter and line plots.catplot()creates categorical plots such as box, violin, bar, and strip plots.displot()creates distribution plots such as histograms, KDEs, and empirical cumulative distributions.
The row and col parameters split data into separate panels, while col_wrap can wrap many column facets across rows. For example, sns.relplot(data=df, x="time", y="value", col="region", hue="group", kind="line") creates one panel per region.
Faceting supports consistent comparisons because panels share a common visual structure. Nevertheless, too many facets, inconsistent scales, or sparse subsets can reduce clarity.
What is a pair plot? Explain its components, uses, and limitations.
A pair plot displays pairwise relationships among multiple numeric variables and is created with sns.pairplot().
Its components are:
- Off-diagonal cells containing scatter plots or another selected bivariate plot.
- Diagonal cells showing the distribution of each individual variable.
- Optional coloring by category through
hue.
It is useful during exploratory data analysis for identifying correlation, clusters, nonlinear patterns, class separation, and outliers. For example, sns.pairplot(data=df, hue="species") compares measurements by species.
Its main limitation is poor scalability. For variables, the grid contains panels, so execution time and visual complexity rise rapidly. Relevant variables should therefore be selected before creating the plot.
Explain how a correlation heatmap is created and interpreted using Seaborn.
A correlation heatmap represents a correlation matrix with color. The usual procedure is:
- Select numeric variables.
- Calculate the matrix using
corr = df.corr(numeric_only=True). - Draw it using
sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1, center=0).
For Pearson correlation, the coefficient is
Values near indicate strong positive linear association, values near indicate strong negative linear association, and values near indicate little linear association. Annotation displays exact values, and centering the diverging palette at zero improves interpretation. Correlation does not establish causation and may fail to reveal nonlinear relationships.
Describe how regression relationships can be visualized with regplot() and lmplot().
sns.regplot() is an axes-level function that commonly draws observations, a fitted regression line, and an uncertainty interval. It is useful when a regression view must be inserted into an existing subplot.
sns.lmplot() is a figure-level function built for regression visualization with DataFrame semantics. It can produce facets using row and col and distinguish groups using hue.
A simple linear model has the form
where is the intercept, is the slope, and represents unexplained variation.
The graph helps assess direction, approximate linearity, group differences, uncertainty, and influential observations. A fitted line is descriptive evidence and should not automatically be interpreted as proof of causation.
Explain how Seaborn plots can be customized using Matplotlib.
Because Seaborn is built on Matplotlib, its plots can be customized through Matplotlib objects and functions.
For an axes-level plot, the returned object can be stored and modified:
ax = sns.boxplot(data=df, x="group", y="score")
Common operations include:
ax.set_title("Scores by Group")to set a title.ax.set_xlabel("Group")andax.set_ylabel("Score")to label axes.ax.tick_params(axis="x", rotation=45)to rotate labels.ax.legend(title="Category")to modify the legend.plt.figure(figsize=(8, 5))to set figure size before an axes-level plot.plt.tight_layout()to improve spacing.plt.savefig("plot.png", dpi=300, bbox_inches="tight")to save the result.
This combination provides Seaborn's convenient statistical interface and Matplotlib's detailed control.
Discuss the effects of missing values, outliers, and overplotting on Seaborn visualizations, and suggest suitable remedies.
Missing values may cause observations to be omitted from a plot or from a statistical estimate. Their pattern should be examined before visualization, and removal or imputation should be justified.
Outliers can stretch axis limits, obscure the main distribution, and strongly influence means or regression lines. Remedies include checking data validity, using robust summaries, displaying outliers explicitly, or applying an appropriate transformed scale. Valid observations should not be removed merely to make a plot look cleaner.
Overplotting occurs when many marks overlap. It can be reduced by:
- Applying transparency with
alpha. - Using smaller markers.
- Adding jitter for categorical coordinates.
- Using histograms, density plots, or hexagonal binning.
- Faceting the data into meaningful subsets.
- Sampling only when the sample remains representative.
These problems should be addressed transparently so that the visualization does not misrepresent the data.
Compare wide-form and long-form data in Seaborn and explain when reshaping is necessary.
Long-form data stores each observation in a row and each variable in a column. It supports explicit mappings such as x, y, hue, style, row, and col, making it the most flexible form for Seaborn.
Wide-form data often stores related measurements in separate columns. Seaborn can interpret some wide-form tables directly, but the semantic meaning of columns and indices may be less explicit, and advanced grouping or faceting can be harder.
Reshaping is necessary when column headers actually represent values of a variable. For example, columns named Jan, Feb, and Mar can be transformed with pandas melt() into columns such as month and sales. The resulting long-form table allows sns.lineplot(data=long_df, x="month", y="sales", hue="store") and supports clearer statistical grouping.
Design and justify a Seaborn-based exploratory visualization workflow for a dataset containing sales, profit, region, product category, and date.
A suitable workflow is:
- Inspect and prepare the data: Check types, duplicates, missing values, and invalid values. Convert the date column to a datetime type and derive useful fields such as month or year.
- Examine individual distributions: Use
histplot()for sales and profit andcountplot()for category or region frequencies. - Compare categories: Use
boxplot()orviolinplot()to compare profit across product categories and regions. - Study relationships: Use
scatterplot()with sales on the -axis, profit on the -axis, and region mapped tohue. - Analyze time trends: Aggregate at an appropriate time level and use
lineplot()to compare sales trends by region. - Use faceting: Apply
relplot()with one facet per category if a single chart becomes crowded. - Check numeric associations: Create a correlation heatmap, while remembering that correlation does not prove causation.
- Refine presentation: Add descriptive titles, units, accessible colors, readable legends, and consistent axis scales.
Each chart should answer a defined question, and conclusions should consider sample size, uncertainty, outliers, and possible confounding variables.
Define Seaborn and explain its role in Python data visualization.
Seaborn is a high-level Python library used to create attractive and informative statistical graphics. It is built on top of Matplotlib and integrates closely with pandas data structures.
Its main roles are:
- Providing simple functions for complex statistical visualizations.
- Applying attractive default themes and color palettes.
- Supporting DataFrames through column-name-based plotting.
- Visualizing relationships, distributions, and categorical data.
- Performing operations such as statistical aggregation and confidence-interval estimation automatically.
For example, sns.scatterplot(data=df, x="height", y="weight") creates a scatter plot directly from DataFrame columns.
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 →