7.9: Practical Examples with Python- Code and Outputs
- Page ID
- 48087
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\ket}[1]{\left| #1 \right>}\)
\(\newcommand{\bra}[1]{\left< #1 \right|}\)
\(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
\(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
\(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
\(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
\(\newcommand{\expect}[1]{\langle #1 \rangle}\)
\(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)
Practical Examples with Python- Code and OutputsEdit
To solidify these concepts, let’s walk through a few practical examples using Python’s Matplotlib and Seaborn libraries. These examples will demonstrate creating common chart types and applying some of the principles discussed. (Even if you’re not deeply familiar with Python, the purpose here is to illustrate the process and result of visualization—focus on the output and interpretation.)
Example 1: Bar Chart of Categorical Data.
Suppose we have a simple dataset of three product categories and their sales in millions. We want to create a bar chart to compare sales across these categories. Using Matplotlib:
import matplotlib.pyplot as plt
categories = ["Category A", "Category B", "Category C"]
sales = [10, 15, 7] # in millions
plt.figure(figsize=(5,4))
plt.bar(categories, sales, color=['skyblue', 'skyblue', 'skyblue'])
plt.title("Sales by Product Category")
plt.xlabel("Product Category")
plt.ylabel("Sales (Millions)")
plt.ylim(0, 16) # ensure y-axis starts at 0 and goes a bit above max for clarity
plt.show()
This code produces a straightforward vertical bar chart. All bars are given the same color for consistency (skyblue). The y-axis starts at 0 (very important for bar charts) and goes to 16 to comfortably fit the highest value 15. The resulting chart shows Category B with the tallest bar (15 million in sales), Category A next (10), and Category C smallest (7). We’ve added a title and axis labels for clarity. From this chart, one can immediately see which category is highest or lowest, fulfilling the task of comparison. In a real scenario, we might use this to emphasize that Category B is the top performer, for instance.
Design note: If one category was the focus, we could color it differently to highlight it. Also, since there are only three categories, labeling each bar with the exact value could be a nice addition (either on top of bars or inside). Matplotlib allows adding plt.text(x, y, label) to place such labels. In our simple output, the relative heights likely suffice.
Example 2: Line Chart of a Time Series.
Imagine we have monthly data for the number of website visitors over a year. We want to show the trend across 12 months. We’ll use a line chart:
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
visitors = [120, 135, 150, 160, 170, 180, 200, 210, 205, 190, 175, 160] # in thousands
plt.figure(figsize=(6,4))
plt.plot(months, visitors, marker='o', color='teal')
plt.title("Website Visitors in 2025")
plt.xlabel("Month")
plt.ylabel("Visitors (thousands)")
plt.grid(True, axis='y', linestyle='--', alpha=0.5) # add horizontal gridlines for readability
plt.show()
This would draw a teal line connecting monthly visitor counts, with circle markers at each month. The trend here is clearly upward from Jan to Aug (peaking in August), then a decline toward December. The chart includes gridlines on the y-axis to help read values (optional). The use of a marker at each data point can make it easier to see exact months. The title and labels make it self-contained. If presenting this, one might annotate August as the peak (210k visitors) and perhaps note the seasonal decline in the fall. This line chart effectively communicates a trend over time — viewers can see the rise and fall pattern across the year.
Design note: We used a single color for the line. If we had multiple years to compare, we’d add multiple plt.plot calls with different colors and a legend. We’d also ensure not to clutter too many lines. In terms of clarity, since months are categorical (ordered), plotting them on the x-axis as labels is fine. If it were many years, a time-series axis (e.g., using actual datetime types) would be appropriate.
Example 3: Scatter Plot with Two Variables.
Let’s use the classic Iris dataset to plot a scatter of petal length vs petal width, and see the relationship (also color by species to see clustering). Using Seaborn for convenience:
import seaborn as sns
iris = sns.load_dataset("iris") # load Iris dataset (if available in seaborn)
plt.figure(figsize=(5,4))
sns.scatterplot(data=iris, x="petal_length", y="petal_width", hue="species", palette="deep")
plt.title("Iris Petal Dimensions")
plt.xlabel("Petal Length (cm)")
plt.ylabel("Petal Width (cm)")
plt.show()
This would produce a scatter plot where each point is a flower sample, positioned by its petal length and width. Points are colored by species (setosa, versicolor, virginica). From the output, typically we’d observe that Iris setosa points cluster separately (with smaller petal dimensions), while versicolor and virginica overlap more but virginica tends toward larger petals. The scatter plot reveals a strong positive correlation between petal length and width (as expected botanically). By coloring the species, we add a third dimension of information, making it evident how the species differ in this feature space. The use of Seaborn simplifies adding the legend and coloring automatically.
Design note: We included a legend via the hue parameter. If printing in black and white, one might additionally differentiate species by marker style (Seaborn can do that with style= parameter) or ensure annotations. But in color, the three hues (by default perhaps blue, orange, green for example) will distinguish the species. We gave the plot a descriptive title and axis labels with units, which is important for interpretation. This kind of plot might be used exploratorily to see if species are separable or to illustrate an example of correlation in a lecture.
Example 4: Heatmap of a Correlation Matrix.
Finally, let’s illustrate a heatmap. We’ll take the Iris dataset’s numeric features and compute the correlation matrix, then plot that as a heatmap to see how each pair of measurements correlates:
import numpy as np
corr = iris.iloc[:, 0:4].corr() # correlation of the first 4 columns (sepal length, width, petal length, width)
plt.figure(figsize=(4,3))
sns.heatmap(corr, annot=True, cmap="YlGnBu", linewidths=0.5)
plt.title("Correlation of Iris Features")
plt.show()
This code uses Seaborn’s heatmap function. We set annot=True to write the correlation coefficients in each cell, and a colormap from yellow to green to blue (where, typically, yellow might be low correlations and blue high correlations in this palette). The output heatmap will be a 4x4 grid (since there are 4 features). We expect to see, for example, petal length is very highly correlated with petal width (a number close to 0.96 perhaps, and the corresponding cell colored in a deep shade indicating high correlation). Sepal length and sepal width might have a lower correlation (even slightly negative in some Iris versions), which the color will show as lighter. The diagonal is all 1.0 (a feature correlates with itself) and often one might blank or darken those out, but here annotating them as 1.00 is fine. This heatmap allows us to quickly identify which features move together. The annotation makes it precise, while the color gives an at-a-glance sense of high vs low correlation.
Design note: We included grid lines (linewidths=0.5) to separate cells. The chosen colormap YlGnBu is perceptually ordered and colorblind-friendly to an extent (since it varies in lightness from yellow to blue). Another design consideration: since correlation ranges from -1 to 1, a diverging palette (like coolwarm) could be used to highlight positive vs negative differently. In Iris data, most correlations are positive, so a sequential palette is okay. We also included a title. If presenting, we would explain that darker blue means stronger positive correlation, and one can see petal measurements are strongly correlated with each other, whereas sepal width is not strongly correlated with the others, etc. This example reinforces how a heatmap can succinctly communicate a whole matrix of relationships.
These examples demonstrate how a few lines of code can create common chart types. In practice, one would further refine these visuals (adjust fonts, sizes, maybe add annotations or adjust figure sizes for readability in a document). The outputs, however, already encapsulate the principles:
- The bar chart provided an easy categorical comparison.
- The line chart highlighted a time trend.
- The scatter plot revealed a relationship and grouping in data.
- The heatmap showed a complex set of relationships in a compact form.
Each was chosen appropriately for the task (we wouldn’t use a pie for the trend or a bar for the correlation matrix, for instance). With Python libraries, we can produce these visuals as part of an analysis pipeline, which is powerful for reproducibility. In other contexts, one could achieve similar results with Excel (for basic charts) or Tableau (for interactive versions), etc.
The key is not the code itself, but understanding what each chart is showing and why it’s useful for that scenario. By reproducing these examples or trying variations (e.g., try changing the data or chart options), students can get a feel for the practical aspects of visualization design and the impact of design choices on the effectiveness of the communication.


