Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
212 views

Python (2024)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
212 views

Python (2024)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 466

Index

Chapter 1 Introduction
1. Purpose
2. About the Execution Environment for Source Code
Chapter 2 For beginners
1. Drawing a Simple Sine Wave Line Plot
2. Bar Chart of Letter Frequency
3. Scatter Plot of Random Points in a Unit Circle
4. Fruit Basket Proportions Visualization
5. Box Plot of Heights Distribution
6. Generate a Heatmap of a Random 10x10 Matrix
7. 3D Surface Plot Visualization
8. Polar Plot of r = θ
9. Simple Network Graph with Artistic Visualization
10. Creating a Bar Chart for Country Populations
11. Scatter Plot Art in Python
12. Plotting a Market Share Pie Chart
13. Histogram of Ages
14. Box Plot Visualization of Weights
15. Generate a Heatmap of a 5x5 Matrix
16. 3D Surface Plot of a Hyperbolic Paraboloid
17. Polar Plot of the Function r = sin(2θ)
18. Simple Network Graph with Artistic Visualization
19. Visual Art with Python: Bar Chart Creation
20. Scatter Plot with Artistic Flair
21. Pie Chart of Class Grades Distribution
22. Histogram of Word Lengths
23. Drawing an Artistic Box Plot of Exam Scores
24. Generate a Heatmap of Random Values
25. 3D Surface Plot Visualization in Python
26. Polar Plot of r = cos(3θ)
27. Scatter Plot Visualization with Artistic Flair
Chapter 3 For advanced
1. Visualizing Product Price Distribution with a Box Plot
2. Generate a 7x7 Heatmap of Random Values
3. 3D Surface Plot of sin(x^2 + y^2)
4. Polar Plot of the Function r = 1 + sin(θ)
5. Simple Network Graph Visualization with Python
6. Create a Visual Art Bar Chart in Python
7. Scatter Plot with Artistic Flair
8. Visualizing Book Distribution in a Library
9. Create a Histogram of Monthly Temperatures
10. Box Plot of Employee Salaries
11. Generate a Heatmap with Random Values for Artistic Visualization
12. Creating a 3D Surface Plot of z = cos(x) * sin(y)
13. Polar Plot of r = 1 - cos(θ)
14. Simple Network Graph Visualization
15. Bar Chart Comparison of Team Scores
16. Scatter Plot Art with Python
17. Pie Chart of Beverage Distribution
18. Histogram of Sentence Lengths
19. Generate a Heatmap of a 9x9 Matrix of Random Values
20. Polar Plot of Sinusoidal Functions
21. Artistic Network Graph Visualization with Python
22. Monthly Expenses Bar Chart
23. Scatter Plot Art with Python
24. Pie Chart of Flower Distribution
25. Plant Height Histogram Visualization
26. Box Plot of Animal Weights
27. Heatmap of a 10x10 Matrix of Random Values
28. 3D Surface Plot Art with Python
29. Polar Plot of the Function r = θ^2
30. Simple Network Graph Visualization
31. Scatter Plot Visual Art in Python
32. Zoo Animal Distribution Pie Chart
33. Histogram of Vehicle Speeds
34. Box Plot of River Lengths
35. Heatmap Visualization of Random Values
36. 3D Surface Plot of z = sin(x) * cos(y)
37. Polar Plot of r = 1 + cos(2θ)
38. Simple Network Graph Visualization
39. Scatter Plot Art with Python
40. Pie Chart of Tree Distribution
41. Event Duration Histogram
42. Box Plot of House Prices
43. Generate a Heatmap of a 12x12 Matrix of Random Values
44. 3D Surface Plot of z = x^2 + y^2
45. Polar Plot of r = sin(3θ)
46. Simple Network Graph Visualization
47. Scatter Plot Art with Python
48. Plotting a Pie Chart of Insect Distribution
49. Visualizing Movie Lengths with a Histogram
50. Mountain Heights Distribution Visualization
51. Heatmap Visualization of a 13x13 Matrix
52. 3D Surface Plot of cos(x^2 + y^2)
53. Polar Plot Art with Python
54. Simple Network Graph with Artistic Visualization
55. Scatter Plot Art with Python
56. Fish Distribution Pie Chart
57. Fruit Weight Histogram
58. Box Plot of Tree Ages
59. Generate a 14x14 Heatmap with Artistic Flair
60. 3D Surface Plot of a Mathematical Function
61. Polar Plot of Cosine Function
62. Scatter Plot with Artistic Flair
63. Histogram Visualization of Song Lengths
64. Box Plot of Rock Weights
65. Generate a Heatmap of a 15x15 Matrix of Random Values
66. Creating a 3D Surface Plot in Python
67. Polar Plot of the Function r = 1 + sin(3θ)
68. Bar Chart of Monthly Steps by Five People
69. Scatter Plot with Artistic Visuals
70. Mineral Distribution Pie Chart
71. Building Heights Histogram Visualization
72. Box Plot for Bridge Lengths
73. Generate a Heatmap of a 16x16 Matrix of Random Values
74. 3D Surface Plot of z = cos(x) * exp(-y^2)
75. Polar Plot of r = sin(5θ)
76. Museum Visitors Bar Chart
77. Scatter Plot with Artistic Flair
78. Pie Chart of Quarry Rock Distribution
79. Vegetable Weight Histogram
80. Skyscraper Heights Distribution Visualization
81. Heatmap of Random 17x17 Matrix
82. 3D Surface Plot of a Mathematical Function
83. Polar Plot of r = 1 - cos(3θ)
84. Artistic Network Visualization with Python
85. Bar Chart for Trees Planted by Organizations
86. Scatter Plot Visual Art with Python
87. Pie Chart of Metal Distribution in a Sample
Chapter 4 Request for review evaluation
Appendix: Execution Environment
Chapter 1 Introduction
1. Purpose

Welcome to this comprehensive guide designed for those who already have
a foundational understanding of programming.
This book is dedicated to the captivating world of visual art through Python,
offering 100 engaging exercises that emphasize artistic expression.
Each exercise is meticulously crafted to include both the source code and
the resulting visual output, accompanied by detailed explanations.
This approach ensures that you can grasp the concepts with ease and see the
immediate impact of your code.
Whether you're commuting, taking a break, or simply looking to expand
your knowledge, this book provides an accessible way to enhance your
skills.
By running the provided source code, you will gain a deeper and more
practical understanding of the material.
Every exercise is visually documented, allowing you to see the beauty of
Python in action.
Dive into this journey of artistic coding and discover the endless
possibilities that Python offers in creating stunning visual art.
2. About the Execution Environment for Source
Code
For information on the execution environment used for the source code in
this book, please refer to the appendix at the end of the book.
Chapter 2 For beginners
1. Drawing a Simple Sine Wave Line Plot
Importance★★★★☆
Difficulty★★☆☆☆
A client from a design agency needs a visually appealing sine wave plot for
a presentation on wave phenomena.
The plot should not only accurately represent a sine wave but also be
artistically styled to catch the audience's attention.
Using Python, create a visually compelling line plot of a sine wave.
Ensure that the plot includes appropriate styling elements like color, line
style, and annotations to enhance its artistic appeal.

【Data Generation Code Example】

import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, color='darkcyan', linestyle='--', linewidth=2, label='Sine
Wave')
plt.title('Artistic Sine Wave Plot', fontsize=20, fontweight='bold')
plt.xlabel('X-axis (radians)', fontsize=14)
plt.ylabel('Y-axis', fontsize=14)
plt.axhline(0, color='grey', linewidth=0.8)
plt.axvline(np.pi, color='grey', linewidth=0.8, linestyle=':')
plt.legend(loc='upper right')
plt.grid(True, which='both', linestyle=':', linewidth=0.5)
plt.annotate('Peak', xy=(np.pi / 2, 1), xytext=(np.pi / 2, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
fontsize=12, fontweight='bold', color='purple')
plt.show()

To draw an artistic sine wave plot, we begin by generating the data for the
sine wave.
Using NumPy, we create an array of x-values ranging from 0 to 2π and
compute the corresponding y-values using the sine function.
We import the necessary libraries, numpy for numerical operations and
matplotlib.pyplot for plotting.
Next, we set up the figure size to ensure the plot is visually appealing.
We plot the sine wave using a dark cyan color and dashed line style to add
artistic flair.
The line width is increased for better visibility.
We add a title to the plot with a larger, bold font to make it stand out.
The x and y axis labels are also added with a larger font for clarity.
Horizontal and vertical reference lines (axhline and axvline) are included
for visual reference, with the vertical line placed at π.
We style the grid with dotted lines for a subtle effect.
To highlight specific points, we use the annotate function. In this example,
we annotate the peak of the sine wave with an arrow and text, using a bold
font and a distinct color.
Finally, we display the plot using plt.show(). This approach not only
demonstrates the sine wave but also ensures the plot is artistically styled to
capture attention.
【Trivia】
‣ The sine wave is a fundamental waveform in mathematics and physics,
often used to describe oscillatory phenomena such as sound waves and
alternating current.
‣ In data visualization, the use of color, line styles, and annotations can
significantly enhance the interpretability and aesthetic appeal of a plot.
‣ The matplotlib library is highly versatile and allows for extensive
customization of plots, making it a powerful tool for creating both scientific
and artistic visualizations.
2. Bar Chart of Letter Frequency
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst working for a publishing company. Your task is to
analyze the frequency of letters in a given string from a book excerpt.
Create a Python script that generates a bar chart showing the frequency of
each letter in the string. The bar chart should be visually appealing,
emphasizing artistic elements such as color and style. Use the following
string as input data: "To be, or not to be, that is the question."
【Data Generation Code Example】

import collections
import matplotlib.pyplot as plt
import numpy as np
import string
data = "To be, or not to be, that is the question."
data = data.lower()
data = ''.join(filter(lambda x: x in string.ascii_lowercase, data))
counter = collections.Counter(data)
letters, counts = zip(*counter.items())
indices = np.arange(len(letters))
plt.bar(indices, counts, color='skyblue')
plt.xticks(indices, letters)
plt.xlabel('Letters')
plt.ylabel('Frequency')
plt.title('Frequency of Letters in the Given String')
plt.show()
【Diagram Answer】

【Code Answer】

import collections
import matplotlib.pyplot as plt
import numpy as np
import string
data = "To be, or not to be, that is the question."
data = data.lower()
data = ''.join(filter(lambda x: x in string.ascii_lowercase, data))
counter = collections.Counter(data)
letters, counts = zip(*counter.items())
indices = np.arange(len(letters))
plt.bar(indices, counts, color='skyblue')
plt.xticks(indices, letters)
plt.xlabel('Letters')
plt.ylabel('Frequency')
plt.title('Frequency of Letters in the Given String')
plt.show()

To create a visually appealing bar chart of letter frequency in a given string,


we start by importing necessary libraries: collections for counting letter
frequency, matplotlib.pyplot for plotting, numpy for numerical operations,
and string for filtering characters.
First, the input string is converted to lowercase to ensure case insensitivity.
Next, we filter out non-alphabetic characters using a combination of filter
and string.ascii_lowercase.
We then use collections.Counter to count the frequency of each letter.
The zip(*counter.items()) function is used to separate the letters and their
counts into two lists.
We create an array of indices for the x-axis using np.arange(len(letters)).
The plt.bar function is used to create the bar chart with sky blue bars.
We set the x-ticks to the letters and label the axes accordingly.
Finally, we set the title and display the chart using plt.show().
This approach ensures that the bar chart is not only informative but also
visually appealing, emphasizing artistic elements.
【Trivia】
‣ The collections.Counter class is a powerful tool for counting hashable
objects in Python. It is a subclass of the dictionary and provides additional
functionalities for counting elements.
‣ matplotlib is one of the most widely used plotting libraries in Python,
known for its flexibility and extensive range of plotting options. It can
generate plots, histograms, power spectra, bar charts, error charts, scatter
plots, etc.
‣ The filter function in Python is used to construct an iterator from
elements of an iterable for which a function returns true. In this case, it is
used to filter out non-alphabetic characters.
‣ The zip function in Python is used to combine multiple iterables into a
single iterable of tuples. The * operator is used to unpack the dictionary
items into separate lists of keys and values.
3. Scatter Plot of Random Points in a Unit Circle
Importance★★★★☆
Difficulty★★★☆☆
A client in the visual arts industry requires a visually appealing scatter plot
for an upcoming presentation.
The scatter plot should display random points within a unit circle.
Your task is to generate this scatter plot using Python, focusing on creating
a visually engaging and artistic representation.
Ensure the points are randomly distributed within the circle and utilize
creative plotting techniques to enhance the visual appeal.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
## Generate random points within a unit circle
num_points = 500
angles = np.random.uniform(0, 2 * np.pi, num_points) # Random angles
radii = np.sqrt(np.random.uniform(0, 1, num_points)) # Random radii
x_points = radii * np.cos(angles)
y_points = radii * np.sin(angles)
## Plot the points
plt.figure(figsize=(8, 8))
plt.scatter(x_points, y_points, c='blue', alpha=0.6, edgecolors='w', s=80)
plt.title('Scatter Plot of Random Points in a Unit Circle')
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
## Generate random points within a unit circle
num_points = 500
angles = np.random.uniform(0, 2 * np.pi, num_points) # Random angles
radii = np.sqrt(np.random.uniform(0, 1, num_points)) # Random radii
x_points = radii * np.cos(angles)
y_points = radii * np.sin(angles)
## Plot the points
plt.figure(figsize=(8, 8))
plt.scatter(x_points, y_points, c='blue', alpha=0.6, edgecolors='w', s=80)
# Blue points with white edges and transparency
plt.title('Scatter Plot of Random Points in a Unit Circle')
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.gca().set_aspect('equal', adjustable='box') # Ensure the aspect ratio is
equal to keep the circle shape
plt.grid(True, which='both', linestyle='--', linewidth=0.5) # Adding grid
for better visual reference
plt.show()

To create a visually appealing scatter plot of random points within a unit


circle, we need to start by generating points that lie within the circle.
We use polar coordinates (angle and radius) for this purpose because it
simplifies the generation process.
We generate random angles uniformly distributed between 0 and 2π2\pi2π,
and random radii that follow a uniform distribution from 0 to 1, but we take
the square root of these radii to ensure an even distribution within the
circle.Next, we convert these polar coordinates to Cartesian coordinates
using the formulas x=rcos⁡(θ)x = r \cos(\theta)x=rcos(θ) and y=rsin⁡(θ)y = r
\sin(\theta)y=rsin(θ), where rrr is the radius and θ\thetaθ is the angle. This
gives us the xxx and yyy coordinates of the points.In the plotting section,
we use matplotlib to create the scatter plot. We set the figure size to 8x8 for
better visibility. We use the scatter function to plot the points, setting the
color to blue and adding some transparency for a nicer visual effect. The
edge color is set to white to make the points stand out more against the plot
background.We set the aspect ratio to 'equal' using
plt.gca().set_aspect('equal', adjustable='box') to ensure the circle retains its
shape. Adding a grid with dashed lines and light width enhances the visual
reference, making the plot more professional and easier to interpret.This
exercise helps you practice generating random points within a defined
shape and using creative plotting techniques to enhance the visual appeal,
which is crucial for making data presentations more engaging and effective.
【Trivia】
‣ The method of generating random points within a unit circle using polar
coordinates ensures an even distribution, avoiding clustering that would
occur if Cartesian coordinates were used directly.
‣ Visual appeal in data presentations can significantly impact audience
engagement and retention of information, making artistic plotting an
important skill for data scientists and analysts.
‣ Matplotlib is a powerful plotting library in Python, providing extensive
customization options for creating professional and aesthetically pleasing
plots. It can be combined with other libraries like seaborn for even more
advanced visualizations.
4. Fruit Basket Proportions Visualization
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst at a grocery store, and you have been tasked with
creating a visual representation of the proportions of different fruits in a
basket.
Your goal is to create a pie chart that artistically displays the proportions of
various fruits.
Use the following data for the fruits and their quantities:
apples: 30, bananas: 20, cherries: 15, dates: 10, and elderberries: 5.
Ensure that the pie chart is visually appealing and includes labels and a title.

【Data Generation Code Example】

import matplotlib.pyplot as plt


fruits = ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries']
quantities = [30, 20, 15, 10, 5]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


fruits = ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries']
quantities = [30, 20, 15, 10, 5]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']
plt.figure(figsize=(8, 8))
plt.pie(quantities, labels=fruits, colors=colors, autopct='%1.1f%%',
startangle=140, pctdistance=0.85, wedgeprops={'edgecolor': 'black'})
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.title('Proportions of Different Fruits in the Basket', fontsize=15)
plt.axis('equal')
plt.show()

To create a visually appealing pie chart in Python, we use the matplotlib


library.
First, we import the necessary library and define the data for the fruits and
their quantities.
The colors list specifies custom colors for each fruit slice to enhance the
visual appeal.
We then create a figure with a specified size using plt.figure(figsize=(8, 8)).
The plt.pie function generates the pie chart, where we pass the quantities,
labels, and colors.
The autopct='%1.1f%%' parameter displays the percentage of each slice,
and startangle=140 rotates the chart for better alignment.
The pctdistance=0.85 parameter controls the distance of the percentage
labels from the center.
To create a donut-like appearance, we add a white circle at the center using
plt.Circle and add it to the plot with fig.gca().add_artist(centre_circle).
Finally, we set the title of the chart using plt.title and ensure the pie chart is
drawn as a circle with plt.axis('equal').
This approach ensures that the pie chart is not only informative but also
visually engaging.
【Trivia】
‣ The pie chart was invented by William Playfair in 1801.
‣ Pie charts are most effective when displaying data with a limited number
of categories.
‣ Overuse of pie charts can lead to confusion, especially with many
categories or similar proportions.
‣ Alternatives to pie charts include bar charts and donut charts, which can
sometimes convey information more clearly.
5. Box Plot of Heights Distribution
Importance★★★☆☆
Difficulty★★☆☆☆
A clothing company wants to analyze the height distribution of their
customers to better tailor their products.
As a data analyst, you are asked to visualize the distribution of heights of 50
randomly selected customers.
The objective is to create an aesthetically pleasing box plot using Python.
Generate the data for the heights randomly within a reasonable range and
then plot the box plot.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
#Generating random height data
heights = np.random.normal(loc=170, scale=10, size=50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
#Generating random height data
heights = np.random.normal(loc=170, scale=10, size=50)
#Creating the box plot
plt.figure(figsize=(10,6))
plt.boxplot(heights, patch_artist=True,
boxprops=dict(facecolor='lightblue', color='blue'),
medianprops=dict(color='red', linewidth=2),
whiskerprops=dict(color='blue'),
capprops=dict(color='blue'),
flierprops=dict(marker='o', color='red', alpha=0.5))
plt.title('Distribution of Heights')
plt.ylabel('Height (cm)')
plt.show()

To begin with, you need to generate a dataset representing the heights of 50


people.
Using NumPy, you can create random heights following a normal
distribution with a mean of 170 cm and a standard deviation of 10 cm.
This can be done using np.random.normal(loc=170, scale=10, size=50).
Next, to create an aesthetically pleasing box plot, you use Matplotlib.
First, import the necessary libraries: numpy for generating data and
matplotlib.pyplot for plotting.
Generate the heights and store them in a variable.
▸ Create the box plot with plt.boxplot(), using various customization
options to enhance the visual appeal:
patch_artist=True allows the box to be filled with color.
boxprops, medianprops, whiskerprops, capprops, and flierprops allow
customization of different parts of the box plot (e.g., colors, line widths,
markers).
Set the plot title and label the y-axis to make the plot informative.
Finally, display the plot with plt.show().
The result is a visually appealing box plot that effectively communicates the
distribution of the height data.
【Trivia】
‣ Box plots are also known as whisker plots and are a standardized way of
displaying the distribution of data based on a five-number summary:
minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
‣ The box in the box plot represents the interquartile range (IQR), which
contains the middle 50% of the data.
‣ Outliers in the data are shown as individual points beyond the whiskers,
which extend to 1.5 times the IQR from the quartiles.
6. Generate a Heatmap of a Random 10x10 Matrix
Importance★★★☆☆
Difficulty★★☆☆☆
A client has requested a visual representation of a randomly generated
10x10 matrix to analyze data distribution.
Your task is to create a heatmap using Python that not only displays the data
but also emphasizes the artistic aspect of data visualization.
The heatmap should be visually appealing with clear labels and a colorbar.
Generate the 10x10 matrix of random values within your code.
Make sure to use vibrant colors and add titles to make the visualization
stand out.
The goal is to create a piece of visual art using Python's data visualization
libraries.

【Data Generation Code Example】

import numpy as np
matrix = np.random.rand(10, 10)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
matrix = np.random.rand(10, 10)
plt.figure(figsize=(10, 8))
sns.heatmap(matrix, annot=True, fmt=".2f", cmap="coolwarm",
cbar=True)
plt.title("Artistic Heatmap of Random 10x10 Matrix")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

To create an artistic heatmap of a 10x10 matrix with random values, we


start by importing the necessary libraries: NumPy for generating the
random matrix, and Matplotlib and Seaborn for visualization.
First, we generate the 10x10 matrix using np.random.rand(10, 10), which
creates an array of the given shape and populates it with random samples
from a uniform distribution over [0, 1].
Next, we set up the plot using plt.figure(figsize=(10, 8)) to specify the size
of the figure.
We use Seaborn's heatmap function to create the heatmap. The parameters
include the matrix, annot=True to display the values in each cell, fmt=".2f"
to format the annotations to two decimal places, cmap="coolwarm" for a
vibrant color palette, and cbar=True to display the color bar.
Finally, we add titles and labels to the heatmap using plt.title, plt.xlabel, and
plt.ylabel to enhance the artistic aspect and make the visualization more
informative. The plt.show() function is called to display the plot.
【Trivia】
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ The coolwarm colormap is often used in heatmaps for its visually
appealing gradient from cool blue to warm red.
‣ Heatmaps are widely used in various fields such as bioinformatics,
finance, and meteorology to represent data density or intensity.
‣ Adding annotations to heatmaps can significantly enhance the readability
and interpretability of the visualized data.
7. 3D Surface Plot Visualization
Importance★★★☆☆
Difficulty★★★☆☆
A client needs to visualize a complex mathematical function to better
understand its behavior across different variables.
Your task is to create a 3D surface plot of the function z = sin(x) * cos(y).
The plot should be visually appealing and demonstrate artistic value, not
just functional visualization.
The input data should be generated within the code itself.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.cos(y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.cos(y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
ax.set_title('3D Surface Plot of z = sin(x) * cos(y)')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()

To create a visually appealing 3D surface plot, we start by generating the


data for the plot.
We use NumPy to create a grid of x and y values ranging from -5 to 5, with
100 points in each direction.
This is achieved using the linspace and meshgrid functions, which create a
coordinate grid over the specified range.
The z values are computed as the product of sin(x) and cos(y), resulting in
the function z = sin(x) * cos(y).
Next, we set up the plotting environment using Matplotlib.
We import the necessary modules and create a figure with a 3D axis.
The plot_surface method is used to generate the 3D surface plot, with a
colormap applied for better visual distinction.
Titles and labels are added to the axes to provide context and clarity.
The choice of colormap (viridis) adds to the artistic appeal of the plot,
ensuring a smooth gradient of colors that enhance the visual representation
of the data.
The final plot is displayed using plt.show(), providing a clear and
aesthetically pleasing visualization of the function.
【Trivia】
‣ The viridis colormap in Matplotlib is designed to be perceptually
uniform, which means it is easier to interpret visually and is also colorblind-
friendly.
‣ 3D plotting in Matplotlib can be customized with various colormaps,
lighting effects, and contour lines to enhance the visual appeal and
readability of the plots.
‣ Using meshgrid to create coordinate grids is a common technique in
scientific computing and data visualization, allowing for efficient
computation and visualization of functions over a range of variables.
8. Polar Plot of r = θ
Importance★★★☆☆
Difficulty★★★☆☆
A client wants to visualize the mathematical function r=θr=\theta r=θ in a
polar coordinate system to create an artistic representation for their new art
exhibit.
You are tasked with writing a Python script that generates this polar plot.
Ensure the plot is visually appealing and artistic.
Use a range of θ\theta θ values from 0 to 4π4\pi 4π to create the plot.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 4 * np.pi, 1000)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 4 * np.pi, 1000)
r = theta
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='purple', linewidth=2)
ax.set_title('Polar Plot of r = θ', va='bottom')
plt.show()

To create a visually appealing polar plot of the function r=θr=\theta r=θ, we


first import the necessary libraries: NumPy for numerical operations and
Matplotlib for plotting.
We generate an array of θ\theta θ values ranging from 0 to 4π4\pi 4π using
NumPy's linspace function, which creates 1000 evenly spaced values within
this range.
The radial coordinate rrr is set equal to θ\theta θ, as per the function
definition.
We then create a figure with a specified size for better visibility and add a
polar subplot using plt.subplot(111, projection='polar').
The plot is drawn using the plot method, where we specify the color and
line width to enhance the visual appeal.
Finally, we set the title of the plot and display it using plt.show().
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system in
which each point on a plane is determined by a distance from a reference
point and an angle from a reference direction.
‣ Polar plots are particularly useful in fields such as physics and
engineering, where they are used to represent data that is periodic or has a
circular nature.
‣ The function r=θr=\theta r=θ creates a spiral known as the Archimedean
spiral, named after the ancient Greek mathematician Archimedes. This type
of spiral has the property that the distance between successive turns is
constant.
9. Simple Network Graph with Artistic
Visualization
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst working for a company that wants to visualize the
relationships between different departments.
Your task is to create a visually appealing network graph with 5 nodes and 6
edges to represent these relationships.
The goal is to create a graph that not only shows the connections but also
stands out as an artistic piece.
Use Python to generate the graph and ensure it is aesthetically pleasing.
The nodes should be labeled "A", "B", "C", "D", and "E".
The edges should connect the nodes as follows: A-B, A-C, B-D, C-D, C-E,
and D-E.

【Data Generation Code Example】

import matplotlib.pyplot as plt


import networkx as nx
nodes = ["A", "B", "C", "D", "E"]
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("C", "E"), ("D",
"E")]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import networkx as nx
nodes = ["A", "B", "C", "D", "E"]
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("C", "E"), ("D",
"E")]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G) # Position nodes using Fruchterman-Reingold
force-directed algorithm
plt.figure(figsize=(8, 6))
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='skyblue',
edgecolors='black')
nx.draw_networkx_edges(G, pos, width=2, alpha=0.6, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=14, font_color='black')
plt.title("Artistic Network Graph", fontsize=16)
plt.axis('off') # Hide the axes for better visualization
plt.show()

To create a visually appealing network graph, we use Python's Matplotlib


and NetworkX libraries.
First, we import the necessary libraries.
We define the nodes and edges of the graph.
The nodes represent different departments labeled "A", "B", "C", "D", and
"E".
The edges represent the relationships between these departments.
We then create a graph object using NetworkX and add the nodes and edges
to it.
To position the nodes in an aesthetically pleasing manner, we use the
Fruchterman-Reingold force-directed algorithm provided by NetworkX's
spring_layout function.
This algorithm simulates a physical system where nodes repel each other
like charged particles, and edges act like springs pulling connected nodes
together.
Next, we set up the plot using Matplotlib.
We specify the size of the figure and draw the nodes with a sky-blue color
and black edges.
The edges of the graph are drawn in gray with a slight transparency to give
a soft look.
The labels for the nodes are added in black with a font size of 14 for better
readability.
Finally, we add a title to the graph and hide the axes to enhance the visual
appeal.
The resulting graph is not only informative but also serves as a piece of
visual art.
【Trivia】
‣ Network graphs are widely used in various fields such as social network
analysis, biology, and computer networks to visualize relationships and
interactions.
‣ The Fruchterman-Reingold algorithm is a popular choice for visualizing
networks due to its ability to produce aesthetically pleasing layouts.
‣ Matplotlib and NetworkX are powerful libraries in Python that allow for
extensive customization and visualization of data, making them ideal for
creating artistic and informative graphs.
10. Creating a Bar Chart for Country Populations
Importance★★★☆☆
Difficulty★★☆☆☆
You have been hired by a marketing firm to create a visually appealing bar
chart that compares the populations of five different countries. The goal is
to create a chart that not only presents the data clearly but also stands out
with its artistic visual appeal. Using Python, write the code necessary to
generate this bar chart. The data for the populations is as follows:‣ Country
A: 50 million
‣ Country B: 30 million
‣ Country C: 80 million
‣ Country D: 60 million
‣ Country E: 40 million

【Data Generation Code Example】

# Creating data for the bar chart

countries = ["Country A", "Country B", "Country C", "Country D",


"Country E"] # List of countries
populations = [50, 30, 80, 60, 40] # Corresponding populations in
millions
【Diagram Answer】

【Code Answer】

# Import necessary libraries


import matplotlib.pyplot as plt
# Data for the bar chart
countries = ["Country A", "Country B", "Country C", "Country D",
"Country E"] # List of countries
populations = [50, 30, 80, 60, 40] # Corresponding populations in
millions
# Create the bar chart
plt.figure(figsize=(10, 6)) # Set the figure size for better visual appeal
bars = plt.bar(countries, populations, color=
['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']) # Generate bars with
different colors
# Add artistic elements
plt.title("Population Comparison of Five Countries", fontsize=18,
fontweight='bold') # Title with bold font
plt.xlabel("Countries", fontsize=14, fontweight='bold') # X-axis label
with bold font
plt.ylabel("Population (in millions)", fontsize=14, fontweight='bold') #
Y-axis label with bold font
plt.xticks(fontsize=12, rotation=45) # Rotate x-ticks for better readability
plt.yticks(fontsize=12) # Set y-ticks fontsize
for bar in bars:
plt.gca().text(bar.get_x() + bar.get_width() / 2, bar.get_height() - 5,
str(bar.get_height()),
ha='center', color='black', fontsize=12, fontweight='bold') #
Add text labels inside the bars
plt.grid(axis='y', linestyle='--', alpha=0.7) # Add grid lines for better
readability
plt.tight_layout() # Adjust layout for neatness
plt.show() # Display the chart

To create a visually appealing bar chart in Python, we start by importing the


necessary library, Matplotlib.
We define the data for the countries and their populations.
A figure of size 10x6 inches is created for better visual impact.
The bar function generates the bars, and different colors are applied to each
bar for better distinction and artistic effect.
The title and labels for the x and y axes are added with bold fonts to make
them stand out.
X-ticks are rotated for better readability, especially when there are multiple
categories.
Y-ticks are also adjusted for readability.
Text labels are added inside the bars to show the exact population values.
Grid lines are added along the y-axis to help compare values across bars
more easily.
Finally, tight_layout is used to adjust the spacing of the plot elements for
neatness, and show displays the chart.
【Trivia】
Creating visually appealing charts is not just about presenting data but also
about enhancing readability and engagement.
The choice of colors, fonts, and layout plays a significant role in how the
information is perceived.
Matplotlib offers a variety of customization options to enhance the artistic
appeal of charts, making it a powerful tool for data visualization.
11. Scatter Plot Art in Python
Importance★★★★☆
Difficulty★★★☆☆
You are tasked with creating a visually appealing scatter plot for a client's
presentation. The scatter plot should display 100 data points with varying
colors and sizes to create an artistic and engaging visual. Ensure the data
points are generated randomly.Write a Python code to generate this scatter
plot. The plot should be clear and aesthetically pleasing, emphasizing the
visual art aspect of data visualization.
【Data Generation Code Example】

import numpy as np
np.random.seed(0)
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
【Diagram Answer】

【Code Answer】

import numpy as np ##Importing numpy for random data generation


import matplotlib.pyplot as plt ##Importing matplotlib for plotting
np.random.seed(0) ##Setting seed for reproducibility
x = np.random.rand(100) ##Generating random x coordinates
y = np.random.rand(100) ##Generating random y coordinates
colors = np.random.rand(100) ##Generating random colors
sizes = 1000 * np.random.rand(100) ##Generating random sizes for the
points
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis') ##Creating
scatter plot with varying colors and sizes
plt.colorbar() ##Adding a color bar to show the color scale
plt.title('Artistic Scatter Plot') ##Setting the title of the plot
plt.xlabel('X axis') ##Labeling x axis
plt.ylabel('Y axis') ##Labeling y axis
plt.show() ##Displaying the plot

This exercise aims to teach you how to use Python to create an artistic
scatter plot with a focus on visual aesthetics. The steps involved are as
follows:‣ First, you need to import the necessary libraries, numpy for data
generation and matplotlib for plotting.
‣ The numpy library's random functions are used to generate 100 random
points for the x and y coordinates, ensuring a diverse spread across the plot.
The np.random.seed(0) ensures that the results are reproducible.
‣ Random colors and sizes are also generated using numpy, with colors
scaled between 0 and 1 and sizes scaled up to 1000 to ensure visibility.
‣ The plt.scatter function from matplotlib is used to create the scatter plot.
This function takes the x and y coordinates, colors, sizes, and other
parameters like alpha for transparency and cmap for the color map. The
viridis color map is chosen for its aesthetic appeal.
‣ A color bar is added to the plot using plt.colorbar() to give context to the
color variations.
‣ Titles and labels for the axes are added to make the plot informative.
Finally, plt.show() is used to display the plot.
This approach not only covers the technical aspects of plotting in Python
but also emphasizes the importance of aesthetics in data visualization,
making the data more engaging and easier to understand.
【Trivia】
Scatter plots are not only used for data visualization but are also appreciated
in the field of data art. Data artists use scatter plots and other types of
visualizations to create visually appealing pieces that tell stories or convey
information in an artistic manner. The interplay of color, size, and position
can transform simple data points into compelling visual narratives. The
viridis color map, used in this exercise, is particularly favored for its
perceptual uniformity and aesthetic quality.
12. Plotting a Market Share Pie Chart
Importance★★★★☆
Difficulty★★★☆☆
You have been tasked by a client to visualize the market share distribution
of four major companies in a particular industry. Create a pie chart to
represent the market share of these companies. The companies and their
respective market shares are as follows: Company A (30%), Company B
(25%), Company C (20%), and Company D (25%).
The visualization should be not only informative but also aesthetically
pleasing, focusing on visual art quality in Python.

【Data Generation Code Example】

companies=['Company A','Company B','Company C','Company D']

market_shares=[30,25,20,25]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
companies=['Company A','Company B','Company C','Company D']
market_shares=[30,25,20,25]
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99']
explode=(0.1,0,0,0)
plt.figure(figsize=(8,8))
plt.pie(market_shares, explode=explode, labels=companies,
colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title('Market Share of Companies', fontsize=18)
plt.axis('equal')
plt.show()

This exercise aims to teach how to create visually appealing pie charts
using Python's Matplotlib library. The process begins with importing
necessary libraries, specifically Matplotlib for plotting. Four companies and
their market shares are defined in lists. The colors list specifies custom
colors for each pie slice, and explode creates a separation effect to
emphasize the first slice.
The plt.figure(figsize=(8,8)) line sets the size of the chart, ensuring it is
large enough for detailed viewing. The plt.pie function creates the pie chart,
with parameters such as explode for emphasizing slices, labels for naming
each slice, and colors for custom slice colors. The autopct='%1.1f%%'
argument displays the percentage values on the chart, shadow=True adds a
shadow effect for depth, and startangle=140 rotates the chart for better
orientation. The plt.title function adds a title with a specified font size, and
plt.axis('equal') ensures the pie is drawn as a circle. Finally, plt.show()
displays the chart.
The exercise focuses on creating an informative and aesthetically pleasing
chart, highlighting the use of colors, explosion effects, and title
customization to enhance visual appeal.
【Trivia】
‣ Matplotlib was created by John D. Hunter and is one of the most widely
used data visualization libraries in Python.
‣ The explode parameter in a pie chart is particularly useful for highlighting
specific slices, making the chart more interactive and engaging.
‣ Customizing colors in Matplotlib can be done using various formats such
as named colors, hexadecimal codes, and RGB tuples, offering great
flexibility in design.
13. Histogram of Ages
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst working for a healthcare company. Your task is to
create a visually appealing histogram that represents the ages of 100 people.
The histogram should be not only informative but also artistically engaging.
Generate the age data within the code itself.
Use Python to create this histogram and ensure that it is visually
captivating.
The goal is to focus on the artistic aspect of data visualization.

【Data Generation Code Example】

import random
ages = [random.randint(1, 100) for _ in range(100)]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import random
ages = [random.randint(1, 100) for _ in range(100)]
plt.figure(figsize=(10, 6))
plt.hist(ages, bins=20, color='skyblue', edgecolor='black')
plt.title('Age Distribution of 100 People', fontsize=20, fontweight='bold')
plt.xlabel('Age', fontsize=14, fontweight='bold')
plt.ylabel('Frequency', fontsize=14, fontweight='bold')
plt.grid(True, linestyle='--', alpha=0.7)
plt.axvline(sum(ages)/len(ages), color='red', linestyle='dashed',
linewidth=2, label='Mean Age')
plt.legend()
plt.show()

To create a visually appealing histogram, we start by importing the


necessary libraries: matplotlib.pyplot for plotting and random for generating
random age data.
We then generate a list of 100 random ages between 1 and 100 using a list
comprehension.
In the visualization section, we use plt.figure to set the figure size, ensuring
the plot is large enough to be visually impactful.
The plt.hist function creates the histogram, where we specify 20 bins, a sky-
blue color for the bars, and black edges for better contrast.
To enhance the aesthetics, we add a title and labels with increased font sizes
and bold formatting.
The grid is enabled with a dashed line style and some transparency to make
the plot easier to read without being too distracting.
We also add a vertical dashed line representing the mean age, colored in
red, to provide an additional point of reference.
Finally, we display the legend and show the plot using plt.show.
【Trivia】
‣ The choice of colors and styles in data visualization can significantly
impact the readability and interpretability of the data.
‣ Matplotlib offers a wide range of customization options, including font
properties, line styles, and color maps, allowing for highly personalized and
artistic visualizations.
‣ Adding reference lines, such as the mean or median, can provide
additional context and make the data more informative.
‣ Grid lines can help viewers better understand the data distribution, but
they should be used sparingly to avoid cluttering the plot.
‣ Artistic data visualization is not just about aesthetics but also about
enhancing the communication of data insights effectively.
14. Box Plot Visualization of Weights
Importance★★★★☆
Difficulty★★★☆☆
You are working as a data analyst for a health and wellness company. Your
task is to create a visually appealing box plot to display the distribution of
weights for 50 people. The goal is to present this data in a visually artistic
manner to impress stakeholders during a presentation.
Generate the data within your code and ensure the plot is not only
informative but also aesthetically pleasing.
Write a Python script that generates the data and creates the box plot.

【Data Generation Code Example】

import numpy as np
weights = np.random.normal(70, 10, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Generate random weights data
weights = np.random.normal(70, 10, 50)
# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Create a box plot
sns.boxplot(weights, ax=ax, color='skyblue')
# Add title and labels
ax.set_title('Distribution of Weights of 50 People', fontsize=16,
weight='bold')
ax.set_xlabel('Weights (kg)', fontsize=14)
# Customize the appearance
ax.grid(True, linestyle='--', alpha=0.7)
ax.set_facecolor('#f7f7f7')
# Show the plot
plt.show()

To create a visually appealing box plot of the distribution of weights for 50


people, we first generate the data using NumPy's random.normal function,
which creates a normal distribution of weights with a mean of 70 kg and a
standard deviation of 10 kg.
We then import the necessary libraries: NumPy for data generation,
Matplotlib for plotting, and Seaborn for enhanced visualization aesthetics.
Next, we set up the plot by creating a figure and axis using Matplotlib's
subplots function. The figsize parameter ensures the plot is large enough to
be visually appealing.
Using Seaborn's boxplot function, we create the box plot with the generated
weights data. The color parameter is set to 'skyblue' to give the plot a
pleasant color.
To enhance the visual appeal, we add a title and label the x-axis. The title is
made bold and slightly larger for emphasis.
We further customize the appearance by adding a grid with a dashed line
style and setting the plot's background color to a light grey using the
set_facecolor method. This makes the plot easier to read and more visually
engaging.
Finally, we display the plot using Matplotlib's show function. The result is
an informative and aesthetically pleasing box plot that effectively
communicates the distribution of weights.
【Trivia】
‣ Box plots, also known as box-and-whisker plots, are excellent for
visualizing the distribution of data and identifying outliers.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ Customizing plots with colors, grid lines, and background colors can
significantly enhance the readability and appeal of the visualization, making
it more effective for presentations.
15. Generate a Heatmap of a 5x5 Matrix
Importance★★★☆☆
Difficulty★★☆☆☆
A client has requested a visual representation of a 5x5 matrix filled with
random values.
Your task is to generate and visualize this matrix as a heatmap.
The client emphasizes that the visual appeal and artistic quality of the
heatmap are crucial.
Please ensure that the heatmap is not only functional but also aesthetically
pleasing.
Create the input data within the code.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(5, 5)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(5, 5)
plt.figure(figsize=(8, 6))
sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis", cbar=True,
linewidths=.5, linecolor='white')
plt.title("Artistic Heatmap of 5x5 Matrix")
plt.show()

To create a visually appealing heatmap, we first import the necessary


libraries: numpy for generating random data, matplotlib.pyplot for plotting,
and seaborn for creating the heatmap.
We generate a 5x5 matrix of random values using numpy.random.rand(5,
5).
Next, we set up the plot with plt.figure(figsize=(8, 6)) to ensure the heatmap
has a good size for visualization.
▸ Using seaborn.heatmap, we create the heatmap with several parameters to
enhance its artistic quality:
‣ annot=True adds the numerical values to each cell for clarity.
‣ fmt=".2f" formats these values to two decimal places.
‣ cmap="viridis" applies a visually appealing color map.
‣ cbar=True includes a color bar for reference.
‣ linewidths=.5 and linecolor='white' add white grid lines to separate the
cells, enhancing the visual structure.
Finally, we add a title with plt.title("Artistic Heatmap of 5x5 Matrix") and
display the plot using plt.show().
【Trivia】
‣ Heatmaps are a powerful tool for visualizing data density and patterns,
often used in fields like bioinformatics and finance.
‣ The viridis colormap used in this example is designed to be perceptually
uniform, meaning it is equally readable by viewers with color vision
deficiencies.
‣ Seaborn, built on top of Matplotlib, simplifies the creation of complex
visualizations and enhances their aesthetic appeal.
16. 3D Surface Plot of a Hyperbolic Paraboloid
Importance★★★★☆
Difficulty★★★☆☆
A client in the field of data visualization needs to create an engaging and
artistic 3D surface plot of the function z=x−yz=x^2-y^2z=x−y. They want
the plot to be visually appealing and suitable for presentation purposes.
Your task is to generate this 3D surface plot using Python, focusing on
creating a visually stunning and artistic representation.
Ensure that the plot is not only accurate but also aesthetically pleasing. Use
appropriate color maps, lighting, and other visual enhancements to make
the plot stand out.
Generate the input data within the code itself and do not use any external
files.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z=x-y
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z=x-y
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
ax.set_title('3D Surface Plot of z = x^2 - y^2')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
plt.show()

To create a visually appealing 3D surface plot of the function z=x−yz=x^2-


y^2z=x−y, we use Python's Matplotlib library.
First, we generate the input data using NumPy. The np.linspace function
creates evenly spaced values between -5 and 5 for both the x and y
coordinates. The np.meshgrid function then creates a grid of these
coordinates, which is necessary for plotting the 3D surface. The function
z=x−yz=x^2-y^2z=x−y is applied to these coordinates to generate the z
values.
In the plotting section, we use Matplotlib's figure and add_subplot methods
to create a 3D plot. The plot_surface method is used to create the surface
plot, with the 'viridis' colormap chosen for its aesthetic appeal. The
edgecolor='none' argument ensures that the plot has a smooth appearance
without grid lines.
Titles and labels for the axes are added to make the plot informative. The
colorbar method adds a color bar to the plot, providing a reference for the z
values. This enhances the visual appeal and makes the plot more
informative. Finally, plt.show() displays the plot.
This approach ensures that the plot is not only accurate but also visually
engaging, making it suitable for presentation purposes.
【Trivia】
‣ The function z=x−yz=x^2-y^2z=x−y is known as a hyperbolic
paraboloid. It has a saddle shape and is commonly used in architecture and
design due to its unique geometric properties.
‣ Matplotlib's plot_surface function allows for extensive customization,
including lighting effects, transparency, and various colormaps, which can
significantly enhance the visual quality of 3D plots.
‣ The 'viridis' colormap is often preferred for its perceptual uniformity,
meaning it is visually appealing and easy to interpret across various devices
and for people with color vision deficiencies.
17. Polar Plot of the Function r = sin(2θ)
Importance★★★★☆
Difficulty★★★☆☆
A client wants to visualize the function r=sin⁡(2θ)r=\sin(2\theta)r=sin(2θ) as
a polar plot for an artistic presentation.
Create a Python script that generates this polar plot.
The plot should be visually appealing, with a focus on artistic presentation.
Use vibrant colors and ensure the plot is aesthetically pleasing.
The client does not require any file saving or loading operations.
The plot should be displayed directly.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.sin(2 * theta)
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='magenta', linewidth=2)
ax.set_title('Polar Plot of r = sin(2θ)', va='bottom', fontsize=15,
color='blue')
ax.grid(True, color='lightgray')
plt.show()

To create a visually appealing polar plot of the function


r=sin⁡(2θ)r=\sin(2\theta)r=sin(2θ), we use Python's matplotlib library.
First, we import the necessary libraries: numpy for numerical operations
and matplotlib.pyplot for plotting.
We generate an array of theta values ranging from 0 to 2π2\pi 2π using
numpy's linspace function.
This array is used to compute the corresponding r values using the given
function r=sin⁡(2θ)r=\sin(2\theta)r=sin(2θ).
Next, we create a figure with a size of 8x8 inches to ensure the plot is large
and clear.
We then create a polar subplot using the projection='polar' argument.
The plot is generated with a magenta line of width 2, making it vibrant and
noticeable.
The title of the plot is set to 'Polar Plot of r = sin(2θ)', with a font size of 15
and a blue color for artistic emphasis.
Grid lines are added with a light gray color to enhance readability without
overpowering the plot.
Finally, the plot is displayed using plt.show().
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system in
which each point on a plane is determined by an angle and a distance from a
reference point.
‣ The function r=sin⁡(2θ)r=\sin(2\theta)r=sin(2θ) creates a classic four-petal
rose pattern, which is often used in mathematical art due to its symmetry
and aesthetic appeal.
‣ Matplotlib's polar plotting capabilities allow for the creation of various
artistic and scientific visualizations, making it a versatile tool for both data
analysis and creative projects.
18. Simple Network Graph with Artistic
Visualization
Importance★★★☆☆
Difficulty★★★☆☆
You are a data analyst at a tech company, and your task is to visualize a
simple network graph to represent the relationships between different
departments.
The graph should have 7 nodes and 8 edges.
Your goal is to create a visually appealing network graph using Python,
focusing on artistic elements to make the visualization more engaging.
Use the provided data to generate the graph.

【Data Generation Code Example】

import matplotlib.pyplot as plt


import networkx as nx
nodes = [1, 2, 3, 4, 5, 6, 7]
edges = [(1, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 7), (6, 7), (2, 5)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
nx.draw(G, with_labels=True)
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import networkx as nx
nodes = [1, 2, 3, 4, 5, 6, 7]
edges = [(1, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 7), (6, 7), (2, 5)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G) # Position nodes using Fruchterman-Reingold
force-directed algorithm
plt.figure(figsize=(8, 6)) # Set figure size
nx.draw_networkx_nodes(G, pos, node_color='skyblue', node_size=700,
alpha=0.8)
nx.draw_networkx_edges(G, pos, width=2, alpha=0.6, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title('Artistic Network Graph', fontsize=15)
plt.axis('off') # Turn off the axis
plt.show()

In this exercise, you are tasked with creating a visually appealing network
graph using Python.
The focus is on artistic visualization, which means you should pay attention
to the aesthetics of the graph.
First, you need to import the necessary libraries: matplotlib.pyplot for
plotting and networkx for creating and manipulating the graph.
Next, you define the nodes and edges of the graph.
Nodes represent the entities (in this case, departments), and edges represent
the relationships between them.
You then create a graph object G and add the nodes and edges to it.
For the artistic part, you use the spring_layout function, which positions the
nodes using the Fruchterman-Reingold force-directed algorithm.
This layout algorithm is designed to make the graph look aesthetically
pleasing by minimizing edge crossings and evenly distributing the nodes.
You set the figure size to ensure the graph is large enough to be visually
appealing.
The nx.draw_networkx_nodes function is used to draw the nodes with a
sky-blue color, a size of 700, and an alpha value of 0.8 for slight
transparency.
The nx.draw_networkx_edges function draws the edges with a width of 2,
an alpha value of 0.6 for transparency, and a gray color.
The nx.draw_networkx_labels function adds labels to the nodes with a font
size of 12 and a black color.
Finally, you set the title of the graph to 'Artistic Network Graph', turn off
the axis for a cleaner look, and display the graph using plt.show().
This approach ensures that the network graph is not only functional but also
visually engaging, making it easier to understand and more enjoyable to
look at.
【Trivia】
‣ Network graphs are widely used in various fields such as social network
analysis, biology, and computer networks.
‣ The Fruchterman-Reingold force-directed algorithm is one of the most
popular algorithms for graph layout due to its ability to produce visually
appealing results.
‣ In network visualization, the choice of colors, node sizes, and edge styles
can significantly impact the readability and aesthetics of the graph.
19. Visual Art with Python: Bar Chart Creation
Importance★★★☆☆
Difficulty★★★☆☆
A retail company wants to visualize the monthly sales data of its four
products to identify sales trends and compare performance. Your task is to
create a bar chart to present the sales data of these products over 12 months.
The sales data for each product is given for January to December.Write
Python code to create this bar chart, emphasizing visual aesthetics to make
the chart appealing and informative. You should use Matplotlib to create
this visualization.Data for sales (in units) is as follows:Product A: [150,
200, 170, 180, 220, 210, 190, 230, 240, 250, 260, 300]Product B: [120, 180,
150, 160, 200, 190, 170, 210, 220, 230, 240, 280]Product C: [100, 160, 130,
140, 180, 170, 150, 190, 200, 210, 220, 260]Product D: [130, 190, 160, 170,
210, 200, 180, 220, 230, 240, 250, 290]Use the provided data to create the
bar chart, ensuring that each product is clearly distinguishable with distinct
colors and labeled appropriately.
【Data Generation Code Example】

# Generate data for sales of four products over 12 months


import numpy as np
import pandas as pd
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
product_a = [150, 200, 170, 180, 220, 210, 190, 230, 240, 250, 260, 300]
product_b = [120, 180, 150, 160, 200, 190, 170, 210, 220, 230, 240, 280]
product_c = [100, 160, 130, 140, 180, 170, 150, 190, 200, 210, 220, 260]
product_d = [130, 190, 160, 170, 210, 200, 180, 220, 230, 240, 250, 290]
data = {
"Months": months,
"Product A": product_a,
"Product B": product_b,
"Product C": product_c,
"Product D": product_d
}
sales_data = pd.DataFrame(data)
print(sales_data)
【Diagram Answer】

【Code Answer】

# Import necessary libraries


import matplotlib.pyplot as plt
import numpy as np
# Generate data for sales of four products over 12 months
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
product_a = [150, 200, 170, 180, 220, 210, 190, 230, 240, 250, 260, 300]
product_b = [120, 180, 150, 160, 200, 190, 170, 210, 220, 230, 240, 280]
product_c = [100, 160, 130, 140, 180, 170, 150, 190, 200, 210, 220, 260]
product_d = [130, 190, 160, 170, 210, 200, 180, 220, 230, 240, 250, 290]
# Set the width of the bars and the positions
bar_width = 0.2
r1 = np.arange(len(months))
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
r4 = [x + bar_width for x in r3]
# Create the bar chart
plt.figure(figsize=(14, 8))
plt.bar(r1, product_a, color='blue', width=bar_width, edgecolor='grey',
label='Product A')
plt.bar(r2, product_b, color='green', width=bar_width, edgecolor='grey',
label='Product B')
plt.bar(r3, product_c, color='red', width=bar_width, edgecolor='grey',
label='Product C')
plt.bar(r4, product_d, color='purple', width=bar_width, edgecolor='grey',
label='Product D')
# Add titles and labels
plt.xlabel('Months', fontweight='bold')
plt.ylabel('Sales (Units)', fontweight='bold')
plt.xticks([r + bar_width for r in range(len(months))], months)
plt.title('Monthly Sales Data of Four Products', fontsize=16,
fontweight='bold')
# Add legend
plt.legend()
# Display the bar chart
plt.show()

To create an aesthetically pleasing bar chart in Python, we used the


Matplotlib library.
The first step involved importing necessary libraries: Matplotlib for plotting
and NumPy for numerical operations.
We then defined the sales data for four products over 12 months and stored
it in lists.We set the width of the bars to 0.2 and calculated the positions for
each set of bars using the arange function from NumPy.
This ensures that the bars for different products are placed side by side for
each month.Next, we created the bar chart using the bar function,
specifying the positions, data, colors, and labels for each product.
Distinct colors (blue, green, red, and purple) were used for the bars to make
them easily distinguishable.To enhance readability, we added x and y axis
labels and set the tick positions and labels for the x-axis to represent the
months.
A title was also added to give an overview of the chart's content.Finally, we
added a legend to indicate which color represents which product and
displayed the bar chart using the show function.This approach focuses not
only on creating the chart but also on ensuring it is visually appealing and
informative, meeting the requirement of visual artistry in Python.
【Trivia】
‣ Matplotlib is one of the most widely used libraries for data visualization
in Python due to its versatility and ease of use.
‣ Bar charts are particularly effective for comparing quantities of different
categories and visualizing trends over time.
‣ In Matplotlib, the bar function is used to create bar charts, and it allows
extensive customization options such as colors, edge colors, and widths to
enhance the visual appeal of the chart.
‣ The positioning of bars in grouped bar charts is crucial to avoid overlap
and ensure clarity, which is managed through careful calculation of bar
positions.
20. Scatter Plot with Artistic Flair
Importance★★★★☆
Difficulty★★★☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to showcase the relationship between two variables, with each point having
a unique color and size to enhance the artistic presentation.
Generate a scatter plot of 200 points with different colors and sizes.
Ensure the plot is visually captivating and aesthetically pleasing.
Use Python to create this plot, and make sure to include the necessary code
to generate the input data within the script.

【Data Generation Code Example】

import numpy as np

import matplotlib.pyplot as plt

np.random.seed(0)

x = np.random.rand(200)

y = np.random.rand(200)

colors = np.random.rand(200)

area = (30 * np.random.rand(200))**2 # 0 to 15 point radii


【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(200)
y = np.random.rand(200)
colors = np.random.rand(200)
area = (30 * np.random.rand(200))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create an artistic scatter plot, we first need to generate random data


points for the x and y coordinates.
We use numpy for this purpose, setting a seed to ensure reproducibility.
We generate 200 random values for both x and y coordinates.
Next, we generate random colors and sizes for each point.
The colors array contains random values between 0 and 1, which will be
used to assign different colors to each point.
The area array determines the size of each point, with sizes ranging from 0
to 15 point radii.
In the plotting section, we use matplotlib to create the scatter plot.
The plt.scatter function is used to plot the points, with the s parameter
controlling the size, c parameter controlling the color, and alpha parameter
setting the transparency.
We also add a title and labels for the x and y axes to make the plot more
informative.
Finally, we display the plot using plt.show().
【Trivia】
‣ Scatter plots are a great way to visualize the relationship between two
variables.
‣ The use of different colors and sizes can help highlight patterns and
trends that might not be immediately obvious.
‣ In data visualization, aesthetics play a crucial role in making the data
more engaging and easier to understand.
‣ The alpha parameter in matplotlib controls the transparency of the points,
which can help in visualizing overlapping points more clearly.
21. Pie Chart of Class Grades Distribution
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst hired by a school to visualize the distribution of
grades in a class.
The school wants to see the distribution of grades in a visually appealing
pie chart.
Create a Python script to generate this pie chart using sample data.
Your chart should be not only functional but also artistically pleasing.

【Data Generation Code Example】

import matplotlib.pyplot as plt


import numpy as np
Generate sample data
grades = ['A', 'B', 'C', 'D', 'F']
counts = [12, 15, 7, 5, 1]
Plotting the pie chart
plt.figure(figsize=(8, 8))
colors = plt.cm.Paired(np.arange(len(grades)))
plt.pie(counts, labels=grades, autopct='%1.1f%%', startangle=140,
colors=colors)
plt.title('Distribution of Grades in the Class')
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
grades = ['A', 'B', 'C', 'D', 'F']
counts = [12, 15, 7, 5, 1]
plt.figure(figsize=(10, 10))
colors = plt.cm.Paired(np.arange(len(grades)))
wedges, texts, autotexts = plt.pie(counts, labels=grades,
autopct='%1.1f%%', startangle=140, colors=colors,
textprops=dict(color="w"))
plt.setp(autotexts, size=14, weight="bold")
plt.setp(texts, size=12)
plt.gca().add_artist(plt.Circle((0, 0), 0.7, color='white'))
plt.title('Distribution of Grades in the Class', fontsize=18, weight='bold')
plt.show()

In this exercise, you are tasked with creating a visually appealing pie chart
to represent the distribution of grades in a class.
The goal is to not only plot the data but also ensure that the chart is
artistically pleasing.
First, we import the necessary libraries: matplotlib.pyplot for plotting and
numpy for handling numerical operations.
We then create sample data for grades and their corresponding counts.
To make the pie chart visually appealing, we set the figure size to 10x10
inches.
We use the plt.cm.Paired color map to generate a set of colors for the pie
slices.
The plt.pie function is used to plot the pie chart, with labels for each grade
and percentage values displayed on the slices.
We customize the text properties of the labels and percentage values to
make them more readable by setting their size and weight.
Additionally, we add a white circle at the center of the pie chart using
plt.Circle to create a donut chart effect, which enhances the visual appeal.
Finally, we set the title of the chart with increased font size and bold
weight.
This approach ensures that the pie chart is not only informative but also
aesthetically pleasing, making it easier for the audience to understand the
distribution of grades at a glance.
【Trivia】
‣ The pie chart was first used by William Playfair in 1801.
‣ Donut charts, a variation of pie charts, are often used to make the chart
more readable by focusing on the proportions rather than the whole.
‣ Matplotlib's plt.cm provides a variety of colormaps that can be used to
enhance the visual appeal of charts.
‣ Choosing the right colors and text properties is crucial in data
visualization to ensure that the information is both accessible and engaging.
22. Histogram of Word Lengths
Importance★★★☆☆
Difficulty★★★☆☆
You are tasked with analyzing the lengths of words in a text to better
understand the distribution of word lengths.
Your goal is to create a histogram that visually represents the lengths of 100
different words.
For this exercise, you will generate the input data within the code.
The histogram should be visually appealing and emphasize artistic
elements.
Ensure that the code runs without errors and produces a clear, informative,
and aesthetically pleasing histogram.

【Data Generation Code Example】

import random
import string
# Generate a list of 100 random words
words = [''.join(random.choices(string.ascii_lowercase,
k=random.randint(3, 10))) for _ in range(100)]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import random
import string
# Generate a list of 100 random words
words = [''.join(random.choices(string.ascii_lowercase,
k=random.randint(3, 10))) for _ in range(100)]
# Calculate the length of each word
word_lengths = [len(word) for word in words]
# Create the histogram
plt.figure(figsize=(10, 6))
plt.hist(word_lengths, bins=range(2, 12), edgecolor='black',
color='#69b3a2')
# Add titles and labels
plt.title('Histogram of Word Lengths', fontsize=16)
plt.xlabel('Word Length', fontsize=14)
plt.ylabel('Frequency', fontsize=14)
# Add grid for better readability
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Display the histogram
plt.show()

In this exercise, we aim to create a visually appealing histogram that


represents the lengths of 100 randomly generated words.
We start by importing the necessary libraries: matplotlib.pyplot for plotting,
and random and string for generating random words.
We generate 100 random words using a list comprehension, where each
word is composed of random lowercase letters and has a length between 3
and 10 characters.
The lengths of these words are then calculated and stored in a list called
word_lengths.
To create the histogram, we use plt.hist() from the matplotlib library.
We specify the bins parameter to define the range of word lengths we want
to display, ensuring the histogram bars are well-defined.
We set the edgecolor to black for better visual separation between bars and
use a custom color (#69b3a2) to make the histogram more aesthetically
pleasing.
We add a title and labels to the x and y axes to provide context to the
viewer.
A grid is also added to the y-axis to enhance readability.
Finally, we display the histogram using plt.show().
This approach ensures that the histogram is not only informative but also
visually engaging, adhering to the principles of artistic data visualization.
【Trivia】
‣ Histograms are a type of bar chart that represents the distribution of
numerical data.
‣ The choice of bin size can significantly affect the appearance and
interpretability of a histogram.
‣ Matplotlib is one of the most widely used libraries in Python for creating
static, interactive, and animated visualizations.
‣ The color scheme and grid lines can greatly enhance the readability and
aesthetic appeal of a histogram.
‣ Data visualization is a crucial skill in data science, helping to uncover
patterns, trends, and insights from data.
23. Drawing an Artistic Box Plot of Exam Scores
Importance★★★☆☆
Difficulty★★☆☆☆
A client has asked you to create a visually stunning box plot to represent the
distribution of exam scores for 30 students.
The client emphasizes that the visual appeal of the plot is of utmost
importance.
You need to generate the data within your code and then create the box plot
using Python.
Ensure that the plot is not only informative but also aesthetically pleasing.

【Data Generation Code Example】

import numpy as np
# Generate random exam scores for 30 students
exam_scores = np.random.randint(50, 100, 30)
print(exam_scores)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Generate random exam scores for 30 students
exam_scores = np.random.randint(50, 100, 30)
# Set the style of the plot
sns.set(style="whitegrid")
# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Create the box plot
sns.boxplot(data=exam_scores, ax=ax, palette="pastel")
# Set the title and labels
ax.set_title("Distribution of Exam Scores", fontsize=20,
fontweight='bold')
ax.set_xlabel("Exam Scores", fontsize=15)
ax.set_ylabel("Values", fontsize=15)
# Customize the appearance
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(1.5)
ax.spines['bottom'].set_linewidth(1.5)
ax.xaxis.set_tick_params(width=1.5)
ax.yaxis.set_tick_params(width=1.5)
# Display the plot
plt.show()

In this exercise, the goal is to create a visually appealing box plot of exam
scores for 30 students using Python.
First, we use the numpy library to generate random exam scores between 50
and 100 for 30 students.
This data is then used to create the box plot.
The seaborn library is used to enhance the aesthetics of the plot.
We set the style to "whitegrid" to provide a clean background.
A figure and axis are created using matplotlib.pyplot.
The seaborn.boxplot function is used to create the box plot with a pastel
color palette, which is visually pleasing.
The title and labels are added with increased font sizes and bold formatting
for the title to make the plot more readable and attractive.
The appearance of the plot is further customized by hiding the top and right
spines, and increasing the linewidth of the left and bottom spines.
The tick parameters are also adjusted for better visual impact.
Finally, the plot is displayed using plt.show().
This exercise demonstrates how to combine data visualization techniques
with artistic elements to create an engaging and informative plot.
【Trivia】
‣ The box plot, also known as a whisker plot, was introduced by John
Tukey in 1977 as a way to graphically depict groups of numerical data
through their quartiles.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive statistical graphics.
‣ The customization of plots is crucial in data visualization as it helps in
better understanding and interpretation of the data.
24. Generate a Heatmap of Random Values
Importance★★★☆☆
Difficulty★★☆☆☆
You have been hired by a data visualization company to demonstrate the
artistic side of data science.
Your task is to generate a heatmap using a 6x6 matrix filled with random
values.
This heatmap should not only display the data but also be aesthetically
pleasing, showcasing the power of Python in creating beautiful visual art.
The matrix should be generated within the code, and the heatmap should
have a clear color gradient and appropriate labels.
The goal is to produce a visual that is both informative and artistically
impressive.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(6, 6)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(6, 6)
plt.figure(figsize=(8, 6))
sns.heatmap(data, annot=True, cmap='viridis', cbar=True, linewidths=0.5,
linecolor='white')
plt.title('Heatmap of Random Values')
plt.xlabel('Column')
plt.ylabel('Row')
plt.show()

To create a visually appealing heatmap, start by generating a 6x6 matrix of


random values using NumPy's rand function.
This ensures the data is within the range [0, 1], providing a good base for
color gradients.
Using Matplotlib and Seaborn, set up the figure size to 8x6 inches, giving
the plot a spacious layout.
The Seaborn heatmap function is used to plot the data, with parameters for
annotation (annot=True) to display the values within the cells.
The cmap='viridis' argument specifies the colormap, chosen for its visually
pleasing gradient from blue to yellow.
Adding a color bar (cbar=True) enhances the interpretability of the
heatmap, showing the scale of values.
Line widths and colors (linewidths=0.5, linecolor='white') add a neat grid
separating the cells, increasing readability.
Finally, titles and labels (plt.title, plt.xlabel, plt.ylabel) provide context,
making the visual both informative and artistically attractive.
【Trivia】
‣ Seaborn is a Python visualization library based on Matplotlib that
provides a high-level interface for drawing attractive and informative
statistical graphics.
‣ The 'viridis' colormap is designed to be perceptually uniform, meaning it
is visually linear and retains its gradient clarity even when printed in black
and white.
‣ Annotating heatmaps is particularly useful in data analysis for showing
exact values, aiding in the quick interpretation of the data visualized.
25. 3D Surface Plot Visualization in Python
Importance★★★★☆
Difficulty★★★☆☆
A client wants to visualize a 3D surface plot of the function
z=exp⁡(−x−y)z=\exp(-x^2-y^2)z=exp(−x−y) to better understand its
behavior.
Your task is to create a Python script that generates this 3D surface plot,
focusing on creating an aesthetically pleasing and artistic visualization.
Ensure that the plot is not only functional but also visually appealing.
Use the provided data generation code to create the necessary input data.
The final plot should be displayed when the script is run.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
x, y = np.meshgrid(x, y)
z = np.exp(-x - y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
x, y = np.meshgrid(x, y)
z = np.exp(-x - y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
ax.set_title('3D Surface Plot of $z = \exp(-x^2 - y^2)$')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

To create a visually appealing 3D surface plot in Python, we start by


importing the necessary libraries: numpy for numerical operations and
matplotlib for plotting.
The mpl_toolkits.mplot3d module is used to create 3D plots.
We generate the input data using numpy.linspace to create a range of values
for x and y, and then use numpy.meshgrid to create a grid of these values.
The function z=exp⁡(−x−y)z=\exp(-x^2-y^2)z=exp(−x−y) is then computed
over this grid.
We create a figure and add a 3D subplot using fig.add_subplot(111,
projection='3d').
The ax.plot_surface method is used to plot the surface, with the cmap
parameter set to 'viridis' for a visually appealing color map.
The edgecolor='none' parameter ensures that the plot has a smooth
appearance without grid lines.
Finally, we set the title and labels for the axes to make the plot informative
and display the plot using plt.show().
【Trivia】
‣ The viridis colormap is often preferred for scientific visualization because
it is perceptually uniform, meaning it is easier for the human eye to
interpret.
‣ The numpy.meshgrid function is particularly useful for creating
coordinate matrices, which are essential for plotting functions over a 2D
grid.
‣ The mpl_toolkits.mplot3d module is a part of Matplotlib and provides
tools for creating 3D plots, which can be useful for visualizing complex
data sets in a more intuitive way.
26. Polar Plot of r = cos(3θ)
Importance★★★☆☆
Difficulty★★★☆☆
A client from an art gallery wants to create an artistic representation of a
mathematical function for an upcoming exhibition.
They have chosen the polar function r = cos(3θ) and want you to generate a
visually appealing plot using Python.
Your task is to write a Python script to generate this plot and ensure it is
aesthetically pleasing.
The plot should be colorful and include a title and labels for better
understanding.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.cos(3 * theta)
plt.figure(figsize=(8, 8))
plt.polar(theta, r, color='purple', linewidth=2)
plt.title('Polar Plot of r = cos(3θ)', fontsize=20)
plt.grid(True)
plt.show()

To create a visually appealing polar plot of the function r = cos(3θ), we first


need to import the necessary libraries: numpy and matplotlib.
Numpy is used to generate a range of θ values from 0 to 2π, which is
essential for plotting the function over a full circle.
We then calculate the corresponding r values using the given function r =
cos(3θ).
The matplotlib library provides a polar plotting function, plt.polar(), which
is used to create the polar plot.
In this plot, we set the color of the plot to purple and increase the line width
to make it more visually striking.
We also add a title to the plot and enable the grid for better readability.
Finally, we use plt.show() to display the plot.
This exercise not only demonstrates how to plot polar functions in Python
but also emphasizes the importance of aesthetics in data visualization.
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system in
which each point on a plane is determined by an angle and a distance from a
reference point.
‣ Polar plots are particularly useful in fields such as physics, engineering,
and navigation, where relationships between variables are better represented
in a circular format.
‣ The function r = cos(3θ) creates a three-petaled rose, a type of
mathematical curve known as a rose curve.
27. Scatter Plot Visualization with Artistic Flair
Importance★★★☆☆
Difficulty★★★☆☆
A client wants to create an eye-catching scatter plot for their data
presentation. They need a scatter plot with 300 points, each with different
colors and sizes to make the plot visually appealing. The data for the points
should be generated within the code itself. Ensure that the plot is not only
informative but also artistic in its presentation.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(300)
y = np.random.rand(300)
colors = np.random.rand(300)
sizes = 1000 * np.random.rand(300)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(300)
y = np.random.rand(300)
colors = np.random.rand(300)
sizes = 1000 * np.random.rand(300)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

This exercise focuses on creating a visually appealing scatter plot using


Python's Matplotlib library. The primary goal is to blend data visualization
with artistic elements, making the plot not only informative but also
aesthetically pleasing.
To achieve this, we first generate random data points for the x and y
coordinates using np.random.rand(300), which creates 300 random values
between 0 and 1. These values represent the positions of the points on the
scatter plot.
Next, we generate random colors and sizes for each point. The colors array
is created using np.random.rand(300), which assigns a random color to each
point. The sizes array is created using 1000 * np.random.rand(300), which
assigns a random size to each point, scaled up to make the differences more
noticeable.
In the plotting section, plt.scatter is used to create the scatter plot. The
parameters c=colors and s=sizes ensure that each point has a unique color
and size. The alpha=0.5 parameter makes the points semi-transparent,
adding to the visual appeal. The cmap='viridis' parameter applies a
colormap to the points, enhancing the color diversity.
The plt.colorbar() function adds a color bar to the plot, providing a
reference for the color mapping. Finally, plt.title, plt.xlabel, and plt.ylabel
add a title and labels to the axes, making the plot more informative.
The resulting scatter plot is both functional and artistic, fulfilling the client's
requirement for an eye-catching data presentation.
【Trivia】
‣ The Matplotlib library is one of the most widely used tools for data
visualization in Python. It provides a wide range of plotting capabilities,
from simple line plots to complex 3D visualizations.
‣ The viridis colormap used in this exercise is designed to be perceptually
uniform, meaning it is visually appealing and accessible to people with
color vision deficiencies.
‣ Scatter plots are particularly useful for visualizing the relationship
between two variables and identifying patterns or trends in the data.
‣ The concept of blending data visualization with artistic elements is
known as "data art." It aims to create visual representations of data that are
both informative and aesthetically pleasing.
Chapter 3 For advanced
1. Visualizing Product Price Distribution with a Box
Plot
Importance★★★★☆
Difficulty★★★☆☆
You are working as a data analyst for a retail company. Your manager has
asked you to create a visual representation of the distribution of prices for
50 randomly selected products.
Your task is to draw a box plot of these product prices to help understand
the price distribution and identify any outliers.
Generate random data for 50 product prices ranging from $1 to $1000.
Write Python code to create and display this box plot.

【Data Generation Code Example】

import numpy as np
np.random.seed(42)
prices = np.random.uniform(1, 1000, 50)
prices
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
prices = np.random.uniform(1, 1000, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(prices)
plt.title('Box Plot of Product Prices')
plt.xlabel('Products')
plt.ylabel('Price ($)')
plt.grid(True)
plt.show()

The first step is to import the necessary libraries, which are NumPy and
Matplotlib.
NumPy is used to generate random data for product prices, and Matplotlib
is used to create the box plot.
By setting a seed using np.random.seed(42), we ensure that the random data
generated is reproducible.
The prices array is created using np.random.uniform(1, 1000, 50), which
generates 50 random numbers uniformly distributed between 1 and 1000.
Next, the code creates a box plot using plt.boxplot(prices). The figsize
parameter sets the size of the figure to 10 by 6 inches.
The title, xlabel, and ylabel functions add labels to the plot, making it easier
to understand.
plt.grid(True) adds a grid to the plot, which improves readability. Finally,
plt.show() displays the plot.
Box plots are particularly useful for visualizing the distribution of data
because they show the median, quartiles, and any potential outliers.
This exercise emphasizes creating visually appealing and informative plots,
which is essential for effective data communication.
Remember, the aesthetics of a plot, such as title, labels, and grid, play a
crucial role in making the plot easy to understand and visually pleasing.
【Trivia】
‣ Box plots, also known as whisker plots, were first introduced by John
Tukey in the 1970s.
‣ They are an excellent way to visualize the spread and skewness of data,
as well as to identify outliers.
‣ In a box plot, the box represents the interquartile range (IQR), which
contains the middle 50% of the data.
‣ The line inside the box represents the median, while the "whiskers"
extend to the smallest and largest values within 1.5 times the IQR from the
lower and upper quartiles.
‣ Points outside this range are considered outliers and are typically plotted
as individual dots.
‣ Box plots can be oriented either vertically or horizontally, and they can be
used to compare distributions across multiple groups.
2. Generate a 7x7 Heatmap of Random Values
Importance★★★☆☆
Difficulty★★★☆☆
You are working as a data visualization specialist for a company that wants
to present a visually appealing heatmap to showcase random data patterns.
Your task is to generate a heatmap of a 7x7 matrix filled with random
values.
The heatmap should be artistically appealing and use Python to create the
visualization.
Ensure the heatmap is colorful and aesthetically pleasing.
Use the provided data generation code to create the input data.
Your final output should be a heatmap that is both informative and visually
artistic.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(7, 7)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Generate random data
data = np.random.rand(7, 7)
# Create the heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(data, annot=True, fmt=".2f", cmap='viridis', linewidths=.5,
cbar_kws={'shrink': .8})
plt.title('Artistic Heatmap of Random Values')
plt.show()

To create a visually appealing heatmap, we first need to generate a 7x7


matrix of random values.
This can be done using the numpy library, which allows for easy creation of
random data.
The numpy.random.rand(7, 7) function generates a 7x7 matrix with values
between 0 and 1.
Once the data is generated, we use matplotlib and seaborn libraries to create
the heatmap.
seaborn is particularly useful for creating visually appealing statistical
graphics.
We start by setting the figure size to ensure the heatmap is large enough to
be easily viewed.
The sns.heatmap function is then used to create the heatmap.
We use the annot=True parameter to display the data values on the heatmap
and fmt=".2f" to format these values to two decimal places.
The cmap='viridis' parameter sets the color map to 'viridis', which is a
visually appealing color scheme.
The linewidths=.5 parameter adds thin lines between the cells for better
separation, and cbar_kws={'shrink': .8} shrinks the color bar to 80% of its
original size for better aesthetics.
Finally, we add a title to the heatmap using plt.title and display the plot with
plt.show().
【Trivia】
‣ The viridis color map is designed to be perceptually uniform, meaning it
is equally readable by those with color vision deficiencies.
‣ seaborn is built on top of matplotlib and provides a high-level interface
for drawing attractive statistical graphics.
‣ Heatmaps are particularly useful for visualizing the density of data points
and can be used in various fields such as bioinformatics, finance, and
meteorology.
‣ The annot parameter in sns.heatmap is very useful for displaying the
actual data values within each cell, making the heatmap more informative.
‣ Using different color maps can significantly affect the readability and
aesthetics of the heatmap. Experimenting with different color maps can help
find the most suitable one for your data.
3. 3D Surface Plot of sin(x^2 + y^2)
Importance★★★☆☆
Difficulty★★★☆☆
A client wants to visualize the function
z=sin⁡(x+y)z=\sin(x^2+y^2)z=sin(x+y) as a 3D surface plot. The purpose of
this exercise is not only to create the plot but to do so in a visually
appealing manner, emphasizing the artistic aspect of data visualization
using Python.
Create a Python script that generates this 3D surface plot. The plot should
be aesthetically pleasing, using colors and styles that enhance its visual
appeal. The data for the plot should be generated within the script itself.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x + y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x + y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
ax.set_title('3D Surface Plot of sin(x^2 + y^2)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

To create a visually appealing 3D surface plot of the function


z=sin⁡(x+y)z=\sin(x^2+y^2)z=sin(x+y), we use Python's Matplotlib library.
First, we generate the data points using NumPy. We create a range of values
for xxx and yyy from -5 to 5, using 100 points for each. These points are
then meshed together to form a grid, which will be used to compute the zzz
values. The zzz values are calculated using the given function
sin⁡(x+y)\sin(x^2+y^2)sin(x+y).
Next, we set up the plot using Matplotlib. We create a figure and add a 3D
subplot to it. The plot_surface function is used to create the surface plot.
The cmap parameter is set to 'viridis' to apply a visually appealing color
map. The edgecolor is set to 'none' to remove the grid lines for a cleaner
look.
Finally, we add titles and labels to the axes to make the plot informative.
The plot is then displayed using plt.show(). This process ensures that the
plot is not only accurate but also visually engaging, emphasizing the artistic
aspect of data visualization.
【Trivia】
‣ The viridis color map used in this example is one of the perceptually
uniform color maps provided by Matplotlib. It is designed to be easy to read
and interpret, even for individuals with color vision deficiencies.
‣ The plot_surface function in Matplotlib allows for a wide range of
customizations, including different color maps, lighting effects, and more.
This makes it a powerful tool for creating both scientific and artistic
visualizations.
‣ 3D surface plots are commonly used in various fields such as physics,
engineering, and finance to visualize complex functions and data sets. The
ability to create aesthetically pleasing plots can enhance presentations and
reports, making the data more accessible and engaging to the audience.
4. Polar Plot of the Function r = 1 + sin(θ)
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data visualization specialist working for a company that wants to
create visually appealing and artistic representations of mathematical
functions. Your task is to create a polar plot of the function
r=1+sin⁡(θ)r=1+\sin(\theta)r=1+sin(θ). This plot should not only be accurate
but also aesthetically pleasing, showcasing your ability to create visually
striking graphs using Python.
Create a Python script that generates this polar plot. Ensure that the plot is
visually appealing by customizing colors, line styles, and adding any artistic
elements you think would enhance the visual impact of the plot.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 + np.sin(theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 + np.sin(theta)
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='purple', linestyle='-', linewidth=2)
ax.set_facecolor('black')
ax.grid(color='white', linestyle='--', linewidth=0.5)
ax.set_title('Polar Plot of r = 1 + sin(θ)', color='white', fontsize=15)
plt.show()

To create a visually appealing polar plot of the function


r=1+sin⁡(θ)r=1+\sin(\theta)r=1+sin(θ), we start by importing the necessary
libraries: numpy for numerical operations and matplotlib.pyplot for
plotting. We generate the data for θ\theta θ using np.linspace, which creates
an array of 1000 values between 0 and 2π2\pi 2π. The corresponding rrr
values are computed using the given function
r=1+sin⁡(θ)r=1+\sin(\theta)r=1+sin(θ).
We then create a figure with a specific size to ensure the plot is large
enough to be visually impactful. The subplot function is used to create a
polar plot. The data is plotted with a purple line, which is aesthetically
pleasing and stands out against the black background. The line style is set to
solid with a width of 2 to make it more prominent.
The background color of the plot is set to black to enhance the visual
contrast. The grid lines are customized to be white, dashed, and thin, adding
an artistic touch while still providing reference points. Finally, a title is
added to the plot, with the text color set to white to ensure it is readable
against the dark background.
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system in
which each point on a plane is determined by an angle and a distance from a
reference point.
‣ The function r=1+sin⁡(θ)r=1+\sin(\theta)r=1+sin(θ) creates a shape known
as a cardioid, which is a heart-shaped curve.
‣ Matplotlib's polar plotting capabilities make it easy to create complex and
visually appealing plots with minimal code.
‣ Customizing the aesthetics of a plot, such as colors, line styles, and
background, can significantly enhance the visual impact and make the data
more engaging.
5. Simple Network Graph Visualization with
Python
Importance★★★☆☆
Difficulty★★★☆☆
You are a data analyst working for a small company. Your manager has
asked you to create a simple network graph to visualize the relationships
between different departments in the company. The graph should have 12
nodes representing different departments and 15 edges representing the
interactions between them. Your task is to write Python code that generates
this network graph. The visualization should be aesthetically pleasing and
highlight the connections effectively.
You need to create the data for the nodes and edges within your code.
Generate and display the network graph using Python.

【Data Generation Code Example】

import random
import networkx as nx
random.seed(42)
nodes=['Dept' + str(i) for i in range(1, 13)]
edges=[(random.choice(nodes), random.choice(nodes)) for _ in
range(15)]
【Diagram Answer】

【Code Answer】

import random
import matplotlib.pyplot as plt
import networkx as nx
random.seed(42)
nodes=['Dept' + str(i) for i in range(1, 13)]
edges=[(random.choice(nodes), random.choice(nodes)) for _ in
range(15)]
G=nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos=nx.spring_layout(G)
plt.figure(figsize=(10, 8))
nx.draw_networkx_nodes(G, pos, node_color='skyblue', node_size=700)
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title('Department Interaction Network')
plt.axis('off')
plt.show()

To create an aesthetically pleasing network graph, we start by importing the


necessary libraries: random, matplotlib.pyplot, and networkx.
We then set a random seed for reproducibility and create a list of 12 nodes,
each representing a department. We generate 15 random edges to simulate
interactions between these departments.
A graph object G is created using NetworkX, and nodes and edges are
added to it. We use the spring_layout function to position the nodes in a
visually appealing manner. This layout uses a force-directed algorithm to
space the nodes.
The nodes are drawn with a light blue color and a size that makes them
easily visible. The edges are drawn in gray to show the connections. Labels
are added to the nodes to indicate which department they represent.
Finally, we set the title of the graph to "Department Interaction Network,"
turn off the axis for a cleaner look, and display the graph using plt.show().
【Trivia】
Network graphs are widely used in various fields, such as sociology,
biology, computer science, and business analytics. They help in visualizing
and analyzing relationships between entities. In a business context, they can
illustrate how different departments or teams interact with each other, which
can be crucial for understanding workflow and communication patterns.
The spring layout algorithm used in this exercise is one of many available
in NetworkX, each suited for different types of data and visual
requirements.
6. Create a Visual Art Bar Chart in Python
Importance★★★☆☆
Difficulty★★★★☆
You are working as a data analyst for a marketing company. The company
wants to present the annual number of visitors to four different websites in a
visually appealing way. Your task is to create a bar chart to compare the
number of visitors over a year.
Generate the data for the number of visitors for four different websites over
12 months, then create a bar chart to display this information. Ensure that
the chart is visually appealing and artistic, focusing on aesthetics.
The names of the websites are: "Site A", "Site B", "Site C", and "Site D".
The number of visitors for each site each month should be randomly
generated within a realistic range.
Here is the code to generate the input data:

【Data Generation Code Example】

import numpy as np
import pandas as pd
# Generate random data for 12 months for 4 websites
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"]
data = { "Month": months }
# Adding visitor data for each site
np.random.seed(42) # For reproducibility
data["Site A"] = np.random.randint(5000, 20000, size=12)
data["Site B"] = np.random.randint(7000, 22000, size=12)
data["Site C"] = np.random.randint(6000, 21000, size=12)
data["Site D"] = np.random.randint(8000, 25000, size=12)
df = pd.DataFrame(data)
print(df)
【Diagram Answer】

【Code Answer】

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Generate random data for 12 months for 4 websites
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"]
data = { "Month": months }
# Adding visitor data for each site
np.random.seed(42) # For reproducibility
data["Site A"] = np.random.randint(5000, 20000, size=12)
data["Site B"] = np.random.randint(7000, 22000, size=12)
data["Site C"] = np.random.randint(6000, 21000, size=12)
data["Site D"] = np.random.randint(8000, 25000, size=12)
df = pd.DataFrame(data)
# Plotting the data
plt.figure(figsize=(12, 8))
# Setting the color palette
colors = ["#FF6347", "#4682B4", "#3CB371", "#FFD700"]
# Plot each site
for i, site in enumerate(["Site A", "Site B", "Site C", "Site D"]):
plt.bar(df["Month"], df[site], color=colors[i], label=site)
# Adding titles and labels
plt.title("Monthly Visitors to Websites", fontsize=18, fontweight='bold')
plt.xlabel("Month", fontsize=14)
plt.ylabel("Number of Visitors", fontsize=14)
plt.legend(title="Websites")
# Customizing the plot aesthetics
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.xticks(rotation=45, fontsize=12)
plt.yticks(fontsize=12)
# Adding artistic elements
for i, site in enumerate(["Site A", "Site B", "Site C", "Site D"]):
for month, value in zip(df["Month"], df[site]):
plt.text(month, value + 300, str(value), ha='center', va='bottom',
fontsize=10, color=colors[i])
# Display the plot
plt.tight_layout()
plt.show()

This exercise focuses on creating a visually appealing bar chart in Python


using the matplotlib library.
First, random data is generated for the number of visitors to four different
websites over 12 months. This is achieved using numpy to generate random
integers within a specified range for each month and site. The data is then
organized into a pandas DataFrame for easy manipulation and plotting.
The chart creation process begins by setting up the figure size for better
visualization. A custom color palette is chosen to differentiate between the
four websites clearly. Each website's data is plotted using the bar function,
specifying the colors and labels accordingly.
To enhance the chart's readability and aesthetics, titles and labels are added
with increased font sizes and bold styling. The grid lines are customized to
appear as dashed lines with partial transparency. The x-ticks (months) are
rotated for better alignment, and both x and y-ticks are adjusted for
improved readability.
Additional artistic elements include displaying the exact number of visitors
above each bar. This is done by looping through the data points and using
the text function to place the values just above the bars, ensuring the values
are visible and adding an extra layer of detail to the chart.
Finally, the layout is adjusted to prevent any overlap or cutting off of
elements, and the plot is displayed using plt.show(). This comprehensive
approach not only demonstrates how to create a bar chart but also
emphasizes the importance of aesthetics in data visualization, making the
chart both informative and visually appealing.
【Trivia】
‣ Matplotlib's flexibility allows for extensive customization of plots, which
is crucial for creating visually appealing charts in presentations and reports.
‣ Using custom color palettes can significantly enhance the readability and
attractiveness of charts. Websites like ColorBrewer provide excellent
resources for choosing color schemes.
‣ Adding textual annotations to plots can provide additional context and
insights, making the data easier to understand at a glance.
7. Scatter Plot with Artistic Flair
Importance★★★★☆
Difficulty★★★☆☆
You are tasked with creating a visually appealing scatter plot for a client
who wants to showcase the diversity and beauty of their data points. The
scatter plot should contain 400 points, each with different colors and sizes.
The goal is to create a piece of visual art using Python that emphasizes the
aesthetic quality of the plot. Generate the input data within the code itself.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
# Generate random data for scatter plot
np.random.seed(0)
x = np.random.rand(400)
y = np.random.rand(400)
colors = np.random.rand(400)
area = (30 * np.random.rand(400))**2 # 0 to 15 point radii
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
# Generate random data for scatter plot
np.random.seed(0)
x = np.random.rand(400)
y = np.random.rand(400)
colors = np.random.rand(400)
area = (30 * np.random.rand(400))**2 # 0 to 15 point radii
# Create scatter plot with artistic flair
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create an artistic scatter plot, we first import the necessary libraries:


NumPy for generating random data and Matplotlib for plotting. We set a
random seed to ensure reproducibility of the results. We then generate 400
random points for the x and y coordinates using np.random.rand(400).
Next, we generate random colors for each point using np.random.rand(400),
which produces an array of 400 random values between 0 and 1. These
values will be used to color the points.
We also generate random sizes for each point by first creating an array of
random values between 0 and 1, multiplying them by 30, and then squaring
the result to get a range of sizes. This ensures that the points have varying
sizes, adding to the visual appeal.
Finally, we create the scatter plot using plt.scatter(), passing in the x and y
coordinates, sizes, colors, and setting the alpha parameter to 0.5 to make the
points semi-transparent. We add a title and labels for the x and y axes, and
then display the plot using plt.show(). This results in a visually engaging
scatter plot that emphasizes the artistic aspect of data visualization.
【Trivia】
‣ Scatter plots are a great way to visualize the relationship between two
variables, but they can also be used to create visually appealing graphics.
‣ The alpha parameter in Matplotlib controls the transparency of the points,
allowing for overlapping points to be seen more clearly.
‣ Using random seeds ensures that the generated random data is the same
every time the code is run, which is useful for reproducibility in data
analysis and visualization.
8. Visualizing Book Distribution in a Library
Importance★★★★☆
Difficulty★★★☆☆
You are tasked with creating a visual representation of the distribution of
different types of books in a library.
Your goal is to plot a pie chart that artistically showcases the proportions of
various book genres.
Generate the input data within your code and ensure the visualization is
aesthetically pleasing.
The genres to include are Fiction, Non-Fiction, Science, History, and
Mystery.
Use Python to create this visual art.

【Data Generation Code Example】

import matplotlib.pyplot as plt


genres = ['Fiction', 'Non-Fiction', 'Science', 'History', 'Mystery']
counts = [150, 120, 90, 80, 60]
plt.figure(figsize=(10, 7))
plt.pie(counts, labels=genres, autopct='%1.1f%%', startangle=140)
plt.title('Distribution of Book Genres in the Library')
plt.axis('equal')
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


genres = ['Fiction', 'Non-Fiction', 'Science', 'History', 'Mystery']
counts = [150, 120, 90, 80, 60]
plt.figure(figsize=(10, 7))
plt.pie(counts, labels=genres, autopct='%1.1f%%', startangle=140,
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'], pctdistance=0.85,
wedgeprops={'edgecolor': 'black'})
plt.title('Distribution of Book Genres in the Library', fontsize=18,
color='darkblue')
plt.axis('equal')
plt.show()

To create a visually appealing pie chart in Python, we use the


matplotlib.pyplot library.
First, we define the genres and their respective counts.
The plt.figure(figsize=(10, 7)) function sets the size of the figure.
The plt.pie function is used to create the pie chart.
We pass the counts and labels to this function, and specify
autopct='%1.1f%%' to display the percentage on each slice.
The startangle=140 rotates the start of the pie chart for better visual
distribution.
To enhance the aesthetics, we add colors, set the percentage distance, and
customize the wedge properties.
Finally, we set the title with a specific font size and color, and use
plt.axis('equal') to ensure the pie chart is a circle.
The plt.show() function displays the chart.
【Trivia】
‣ The pie chart was invented by William Playfair in 1801.
‣ Matplotlib is a powerful library in Python for creating static, animated,
and interactive visualizations.
‣ Customizing colors and styles in Matplotlib can significantly enhance the
readability and appeal of your charts.
‣ The wedgeprops parameter in plt.pie allows for detailed customization of
the pie slices, including edge colors and line styles.
9. Create a Histogram of Monthly Temperatures
Importance★★★★☆
Difficulty★★★☆☆
A client requires a detailed visual representation of the temperature
variations over a month for their weather analysis report. Your task is to
create a histogram of the temperatures recorded over a month. Generate a
sample dataset within the code to simulate the temperature data for 30 days.
The goal is to produce a visually appealing histogram using Python that
highlights the distribution of temperatures.
【Data Generation Code Example】

import numpy as np
# Generate random temperature data for 30 days
np.random.seed(42)
temperatures = np.random.normal(loc=25, scale=5, size=30)
print(temperatures)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
# Generate random temperature data for 30 days
np.random.seed(42)
temperatures = np.random.normal(loc=25, scale=5, size=30)
# Create a histogram
plt.figure(figsize=(10, 6)) ##Set the figure size
plt.hist(temperatures, bins=10, color='skyblue', edgecolor='black')
##Create histogram with custom colors
plt.title('Temperature Distribution Over a Month', fontsize=15) ##Add
title with specific font size
plt.xlabel('Temperature (°C)', fontsize=12) ##Label x-axis with specific
font size
plt.ylabel('Frequency', fontsize=12) ##Label y-axis with specific font
size
plt.grid(True, linestyle='--', alpha=0.7) ##Add grid with custom style and
transparency
plt.show() ##Display the histogram

▸ To create a visually appealing histogram of monthly temperatures using


Python, follow these steps:
Import the necessary libraries: NumPy for data generation and Matplotlib
for plotting.
Generate a sample dataset of temperatures for 30 days. In this example, we
use NumPy's random.normal function to create data with a mean of 25°C
and a standard deviation of 5°C. This simulates realistic temperature
variations.
Create the histogram plot using Matplotlib. Set the figure size to 10x6
inches for better visibility. Use the plt.hist function to create the histogram
with 10 bins, a sky blue color for the bars, and black edges for better
contrast.
Add a title and axis labels with specific font sizes to make the plot more
informative. The plt.title, plt.xlabel, and plt.ylabel functions are used for
this purpose.
Enable the grid with a dashed line style and partial transparency to enhance
the visual appeal without overwhelming the plot. The plt.grid function helps
achieve this.
Finally, display the histogram using plt.show. This function renders the plot
on the screen.
By following these steps, you can create a histogram that not only displays
the data effectively but also has a strong visual appeal, which is crucial for
reports and presentations.
【Trivia】
‣ Histograms are a type of bar chart that represents the frequency
distribution of a dataset. They are particularly useful for understanding the
underlying distribution of continuous data.
‣ The number of bins in a histogram can significantly impact the
visualization. Too few bins can oversimplify the data, while too many bins
can make the plot overly complex. Choosing the right number of bins is
essential for accurate data representation.
‣ Matplotlib is one of the most popular Python libraries for data
visualization due to its flexibility and extensive customization options. It
allows users to create a wide range of static, animated, and interactive plots.
10. Box Plot of Employee Salaries
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst at a company and have been asked to visualize the
distribution of salaries for 50 employees to identify any outliers and
understand the overall salary structure.
Create a box plot to display this distribution using Python.
Generate the salary data within your code.

【Data Generation Code Example】

import numpy as np
salaries = np.random.normal(50000, 10000, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
salaries = np.random.normal(50000, 10000, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(salaries)
plt.title('Distribution of Employee Salaries')
plt.ylabel('Salary ($)')
plt.grid(True)
plt.show()
In this exercise, you will create a box plot to visualize the distribution of
employee salaries.
A box plot, also known as a box-and-whisker plot, is a standardized way of
displaying the distribution of data based on a five-number summary:
minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
The box itself represents the interquartile range (IQR), which contains the
middle 50% of the data.
The line inside the box represents the median of the data.
The "whiskers" extend from the box to the smallest and largest values
within 1.5 times the IQR from the quartiles.
Any data points outside this range are considered outliers and are plotted as
individual points.
The provided code uses the numpy library to generate a sample dataset of
50 employee salaries.
The normal function creates a normal distribution with a mean of 50,000
and a standard deviation of 10,000.
The matplotlib.pyplot library is then used to create and display the box plot.
The boxplot function generates the box plot, and additional functions like
title, ylabel, and grid are used to enhance the visual appeal and readability
of the plot.
This exercise emphasizes creating visually appealing and informative plots,
which is a crucial skill for data visualization in Python.
【Trivia】
‣ Box plots were introduced by John Tukey in 1977 as a part of exploratory
data analysis.
‣ They are particularly useful for comparing distributions between several
groups or datasets.
‣ Box plots can reveal skewness, the presence of outliers, and the spread of
the data, making them a powerful tool for initial data analysis.
‣ In some variations, the whiskers can represent different ranges, such as 2
standard deviations from the mean, instead of 1.5 times the IQR.
11. Generate a Heatmap with Random Values for
Artistic Visualization
Importance★★★★☆
Difficulty★★☆☆☆
A client needs a visually appealing representation of data for an art project.
They have asked you to generate a heatmap from an 8x8 matrix of random
values. Use Python to create a heatmap that emphasizes artistic
visualization. Ensure the final output is aesthetically pleasing and suitable
for an art exhibition.Write a Python script that:Generates an 8x8 matrix of
random values.Creates a heatmap from these values.Enhances the heatmap's
visual appeal using artistic elements.Generate the data within your script
and produce the final heatmap visualization. Focus on making the
visualization artistically appealing.
【Data Generation Code Example】

import numpy as np
data = np.random.rand(8, 8)
print(data)
【Diagram Answer】

【Code Answer】

import numpy as np ##Importing numpy for data generation


import matplotlib.pyplot as plt ##Importing matplotlib for plotting
data = np.random.rand(8, 8) ##Generating an 8x8 matrix of random
values
plt.figure(figsize=(8, 8)) ##Setting the figure size
plt.imshow(data, cmap='viridis', interpolation='nearest') ##Creating a
heatmap with the 'viridis' colormap for aesthetic appeal
plt.colorbar() ##Adding a colorbar to the heatmap
plt.title('Artistic Heatmap of Random Values', fontsize=20) ##Setting the
title of the heatmap
plt.xlabel('X Axis', fontsize=14) ##Setting the x-axis label
plt.ylabel('Y Axis', fontsize=14) ##Setting the y-axis label
plt.xticks(fontsize=12) ##Setting x-axis tick labels font size
plt.yticks(fontsize=12) ##Setting y-axis tick labels font size
plt.grid(False) ##Disabling the grid for a cleaner look
plt.show() ##Displaying the heatmap

To create an artistic heatmap, we start by generating an 8x8 matrix of


random values using numpy's rand function. This provides the raw data for
the heatmap.We use matplotlib to plot the heatmap, leveraging the imshow
function. The 'viridis' colormap is chosen for its visually pleasing gradient,
which enhances the artistic appeal. The figure size is set to ensure the
heatmap is clearly visible, and a colorbar is added for reference.A title and
axis labels are included to give context to the visualization. The font sizes
for the title and labels are adjusted for better readability. The grid is
disabled to maintain a clean and uncluttered look.This approach focuses on
creating a visually appealing and artistically relevant representation of the
data, suitable for an art exhibition or similar context.
【Trivia】
‣ The 'viridis' colormap is designed to be perceptually uniform, meaning it
is visually uniform and suitable for viewers with color vision deficiencies.
‣ Heatmaps are widely used in various fields such as biology, meteorology,
and data science to represent complex data visually.
‣ The choice of colormap can significantly impact the interpretability and
aesthetic appeal of a heatmap.
12. Creating a 3D Surface Plot of z = cos(x) * sin(y)
Importance★★★★☆
Difficulty★★★☆☆
A graphic design company wants to visualize the mathematical function z =
cos(x) * sin(y) as a 3D surface plot to use as part of their new advertising
campaign.
Your task is to generate a visually appealing 3D surface plot of this function
using Python.
The x and y values should range from -5 to 5, with increments of 0.1.

【Data Generation Code Example】

import numpy as np
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
x, y = np.meshgrid(x, y)
z = np.cos(x) * np.sin(y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
x, y = np.meshgrid(x, y)
z = np.cos(x) * np.sin(y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
ax.set_title('3D Surface Plot of z = cos(x) * sin(y)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

The purpose of this task is to create a visually appealing 3D surface plot of


the function z = cos(x) * sin(y) using Python.
First, the necessary libraries are imported: numpy for numerical operations,
matplotlib.pyplot for plotting, and mpl_toolkits.mplot3d for 3D plotting.
Next, the range of x and y values is defined from -5 to 5 with increments of
0.1, and the meshgrid function is used to create a grid of these values. The
function z = cos(x) * sin(y) is then calculated over this grid.
A figure is created using plt.figure(), and a 3D subplot is added to this
figure. The plot_surface function is used to generate the 3D surface plot,
with the 'viridis' colormap chosen for its visually appealing gradient.
Finally, the plot is customized with axis labels and a title, and displayed
using plt.show(). This exercise emphasizes creating an aesthetically
pleasing plot, showcasing Python's capabilities for visual art in data
visualization.
【Trivia】
3D surface plots are a powerful tool for visualizing complex functions and
datasets.
They are widely used in various fields such as engineering, physics, and
finance to illustrate how a dependent variable changes with two
independent variables.
Matplotlib is a versatile plotting library in Python, offering extensive
customization options to create high-quality visualizations.
13. Polar Plot of r = 1 - cos(θ)
Importance★★★★☆
Difficulty★★★☆☆
A local art gallery wants to create a visually appealing piece for an
upcoming exhibition. They have decided to use mathematical functions to
generate artistic plots. Your task is to create a polar plot of the function
r=1−cos⁡(θ)r=1-\cos(\theta)r=1−cos(θ) using Python. The plot should be
visually striking, with attention to color and style to make it suitable for an
art exhibition. Ensure that the plot is clear and aesthetically pleasing.
【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 - np.cos(theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000) # Generate theta values
r = 1 - np.cos(theta) # Calculate r values
plt.figure(figsize=(8, 8)) # Create a figure
ax = plt.subplot(111, projection='polar') # Create a polar subplot
ax.plot(theta, r, color='purple', linewidth=2) # Plot the polar graph
ax.set_title('Polar Plot of r = 1 - cos(θ)', fontsize=15, color='darkblue') #
Set title
ax.grid(True) # Show grid
ax.set_facecolor('whitesmoke') # Set background color
plt.show() # Display the plot

To create a visually appealing polar plot of the function r=1−cos⁡(θ)r=1-


\cos(\theta)r=1−cos(θ), we start by importing the necessary libraries: numpy
for numerical operations and matplotlib.pyplot for plotting.
We generate 1000 evenly spaced values of θ\theta θ between 0 and 2π2\pi
2π using np.linspace.
Using these θ\theta θ values, we compute the corresponding rrr values using
the given function r=1−cos⁡(θ)r=1-\cos(\theta)r=1−cos(θ).
We then create a figure with a specified size to ensure the plot is large
enough to be visually striking.
A polar subplot is created using plt.subplot(111, projection='polar'), which
enables us to plot in polar coordinates.
The plot is drawn with a purple line of width 2 for better visibility.
The title of the plot is set with a larger font size and a dark blue color to
make it stand out.
Grid lines are enabled to enhance the visual structure of the plot.
Finally, the background color of the plot is set to 'whitesmoke' to give it a
clean and modern look.
The plot is displayed using plt.show(), which renders the final visual output.
【Trivia】
The function r=1−cos⁡(θ)r=1-\cos(\theta)r=1−cos(θ) is known as a cardioid,
named for its heart-like shape.
Cardioids are a type of limaçon, a family of curves that can be generated by
tracing a point on the circumference of a circle as it rolls around another
circle of the same radius.
These curves have applications in various fields, including acoustics, where
cardioid microphones are designed to capture sound from the front while
reducing noise from the sides and rear.
14. Simple Network Graph Visualization
Importance★★★☆☆
Difficulty★★★☆☆
You are a data analyst working for a company that needs to visualize a
simple network graph for an internal presentation.
Your task is to create a visually appealing network graph with 15 nodes and
20 edges using Python.
Ensure that the graph is not only functional but also aesthetically pleasing
to impress your audience.
The data for the nodes and edges should be generated within the code.

【Data Generation Code Example】

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = range(1, 16)
edges = [(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (4, 8), (4, 9), (5, 10), (5,
11), (6, 12), (6, 13), (7, 14), (7, 15), (8, 9), (10, 11), (12, 13), (14, 15), (1,
15), (2, 14)]
G.add_nodes_from(nodes)
G.add_edges_from(edges)
nx.draw(G, with_labels=True)
plt.show()
【Diagram Answer】

【Code Answer】

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = range(1, 16)
edges = [(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (4, 8), (4, 9), (5, 10), (5,
11), (6, 12), (6, 13), (7, 14), (7, 15), (8, 9), (10, 11), (12, 13), (14, 15), (1,
15), (2, 14)]
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G)
plt.figure(figsize=(10, 10))
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='skyblue',
alpha=0.7)
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray', alpha=0.5)
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title("Simple Network Graph", size=15)
plt.show()

In this task, you are required to create a visually appealing network graph
using Python.
The graph should consist of 15 nodes and 20 edges, and the data for these
nodes and edges should be generated within the code.
To achieve this, we use the networkx library for creating and managing the
graph, and matplotlib for visualizing it.
First, we import the necessary libraries: networkx and matplotlib.pyplot.
We then create an empty graph object G using nx.Graph().
Next, we define the nodes and edges of the graph.
The nodes are simply a range of numbers from 1 to 15.
The edges are defined as pairs of nodes that will be connected.
We add the nodes and edges to the graph using G.add_nodes_from(nodes)
and G.add_edges_from(edges), respectively.
To make the graph visually appealing, we use the spring_layout function to
position the nodes in a way that minimizes edge crossings and evenly
distributes the nodes.
We then create a figure with a specified size using plt.figure(figsize=(10,
10)).
The nodes are drawn with a specific size, color, and transparency using
nx.draw_networkx_nodes.
The edges are drawn with a specified width, color, and transparency using
nx.draw_networkx_edges.
The labels for the nodes are added using nx.draw_networkx_labels.
Finally, we add a title to the graph using plt.title and display the graph using
plt.show().
This approach ensures that the graph is not only functional but also
aesthetically pleasing, making it suitable for presentation purposes.
【Trivia】
‣ The networkx library is a powerful tool for the creation, manipulation,
and study of complex networks of nodes and edges.
‣ The spring_layout function in networkx uses the Fruchterman-Reingold
force-directed algorithm to position nodes in a visually appealing way.
‣ Visualization is a critical aspect of data analysis as it helps in
understanding complex data structures and relationships.
‣ The matplotlib library is one of the most widely used libraries for plotting
in Python, offering a wide range of customization options for creating high-
quality visualizations.
15. Bar Chart Comparison of Team Scores
Importance★★★☆☆
Difficulty★★☆☆☆
A sports tournament organizer needs to visually compare the scores of 5
teams to present the results to stakeholders.
Your task is to create a bar chart that displays the scores of these 5 teams in
a visually appealing manner.
The chart should be designed with a focus on artistic aesthetics to make it
more engaging.
Generate the data within the code and ensure that the chart is both
informative and visually attractive.

【Data Generation Code Example】

import matplotlib.pyplot as plt


import numpy as np
teams = ['Team A', 'Team B', 'Team C', 'Team D', 'Team E']
scores = np.random.randint(50, 100, size=5)
plt.bar(teams, scores)
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
import seaborn as sns
teams = ['Team A', 'Team B', 'Team C', 'Team D', 'Team E']
scores = np.random.randint(50, 100, size=5)
sns.set(style="whitegrid")
palette = sns.color_palette("coolwarm", len(teams))
plt.figure(figsize=(10, 6))
bars = plt.bar(teams, scores, color=palette)
plt.title('Team Scores in Tournament', fontsize=20)
plt.xlabel('Teams', fontsize=15)
plt.ylabel('Scores', fontsize=15)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, yval + 1, round(yval, 2),
ha='center', va='bottom', fontsize=12)
plt.show()

This exercise focuses on creating a visually appealing bar chart using


Python.
The task involves generating random scores for five teams and displaying
these scores in a bar chart.
The code uses the matplotlib library for basic plotting and seaborn for
enhancing the visual aesthetics.
First, the necessary libraries are imported: matplotlib.pyplot for plotting,
numpy for generating random scores, and seaborn for styling.
The teams and their scores are defined, with scores generated randomly
between 50 and 100.
The seaborn.set function is used to set the overall style of the plot, and a
color palette is chosen to make the bars visually appealing.
The plt.figure function is used to set the size of the plot.
The plt.bar function creates the bar chart, with each bar colored according
to the chosen palette.
Titles and labels are added to the chart to make it informative.
The plt.text function is used to annotate each bar with its corresponding
score, enhancing readability.
Finally, plt.show displays the chart.
【Trivia】
‣ The seaborn library is built on top of matplotlib and provides a high-level
interface for drawing attractive statistical graphics.
‣ Using color palettes effectively can significantly enhance the readability
and aesthetic appeal of visualizations.
‣ Annotating charts with data labels can help viewers quickly understand
the data without referring to the axes.
16. Scatter Plot Art with Python
Importance★★★☆☆
Difficulty★★☆☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to attract visitors to their new exhibition. They need a scatter plot with 500
points, each with different colors and sizes, to represent the diversity and
vibrancy of the artworks. The client has asked for a Python code that
generates this scatter plot.
Please write a Python code that generates a scatter plot with 500 points,
where each point has a unique color and size. The plot should be visually
appealing and artistic. The data for the scatter plot should be generated
within the code itself.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
# Generate random data for the scatter plot
np.random.seed(0)
x = np.random.rand(500)
y = np.random.rand(500)
colors = np.random.rand(500)
area = (30 * np.random.rand(500))**2 # 0 to 15 point radii
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
# Generate random data for the scatter plot
np.random.seed(0)
x = np.random.rand(500)
y = np.random.rand(500)
colors = np.random.rand(500)
area = (30 * np.random.rand(500))**2 # 0 to 15 point radii
# Create the scatter plot
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

The goal of this exercise is to create a visually appealing scatter plot using
Python. The scatter plot will contain 500 points, each with a unique color
and size, to represent the diversity and vibrancy of artworks in an
exhibition. This exercise emphasizes the artistic aspect of data visualization,
making it an engaging way to learn about scatter plots and data
visualization in Python.
First, the necessary libraries are imported: numpy for generating random
data and matplotlib.pyplot for creating the plot. The np.random.seed(0)
function ensures that the random numbers generated are the same each time
the code is run, which is useful for reproducibility.
Next, random data for the x and y coordinates of the scatter plot points are
generated using np.random.rand(500). This function generates 500 random
numbers between 0 and 1. The colors array is also generated using
np.random.rand(500), providing a unique color for each point. The area
array is calculated using (30 * np.random.rand(500))**2, which generates
random sizes for the points, scaled to a range of 0 to 15 point radii.
The plt.scatter function is used to create the scatter plot. The parameters x
and y specify the coordinates of the points, s=area sets the sizes of the
points, c=colors sets the colors, and alpha=0.5 sets the transparency of the
points. The plt.title, plt.xlabel, and plt.ylabel functions add a title and labels
to the plot, making it more informative. Finally, plt.show() displays the plot.
【Trivia】
‣ Scatter plots are a powerful tool for visualizing the relationship between
two variables. They are often used in data analysis to identify correlations
and patterns.
‣ The use of color and size in scatter plots can add an additional dimension
of information, making the visualization more informative and engaging.
‣ Matplotlib is one of the most widely used libraries for data visualization
in Python, offering a wide range of plotting functions and customization
options.
‣ The transparency (alpha) parameter in scatter plots can help to visualize
overlapping points, making the plot clearer and more aesthetically pleasing.
17. Pie Chart of Beverage Distribution
Importance★★★☆☆
Difficulty★★☆☆☆
You are tasked with creating a pie chart that shows the distribution of
different types of beverages in a store. This chart will help the store
manager understand which beverages are most popular and adjust the
inventory accordingly. Use the provided data to create this visualization.
The data includes different beverage types and their respective quantities.
【Data Generation Code Example】

# # Create sample data for beverage distribution


import pandas as pd
# # Creating a dictionary with beverage types and their quantities
data = {'Beverage': ['Coffee', 'Tea', 'Juice', 'Soda', 'Water'],
'Quantity': [120, 80, 50, 70, 60]}
# # Converting the dictionary to a DataFrame
df = pd.DataFrame(data)
# # Display the DataFrame
df
【Diagram Answer】

【Code Answer】

# # Import necessary libraries


import pandas as pd
import matplotlib.pyplot as plt
# # Create sample data for beverage distribution
data = {'Beverage': ['Coffee', 'Tea', 'Juice', 'Soda', 'Water'],
'Quantity': [120, 80, 50, 70, 60]}
# # Converting the dictionary to a DataFrame
df = pd.DataFrame(data)
# # Creating the pie chart
plt.figure(figsize=(8,8)) # # Setting the figure size
plt.pie(df['Quantity'], labels=df['Beverage'], autopct='%1.1f%%',
startangle=140) # # Plotting the pie chart with percentages and a start
angle
plt.title('Distribution of Different Types of Beverages') # # Adding the
title
plt.show() # # Display the chart

In this exercise, we aim to create a visually appealing pie chart to represent


the distribution of different types of beverages in a store.
First, we create a dictionary containing the beverage types and their
respective quantities.
We then convert this dictionary into a Pandas DataFrame, which is a
convenient format for handling and manipulating data.
To create the pie chart, we use Matplotlib, a popular Python library for data
visualization.
The plt.pie() function is used to plot the pie chart. The labels parameter is
used to specify the labels for each segment, which in this case are the
beverage types.
The autopct parameter is used to display the percentage distribution of each
segment, formatted to one decimal place.
The startangle parameter rotates the chart to start at a specified angle,
making it more aesthetically pleasing.
We also set the figure size to make the chart larger and more readable.
Finally, we add a title to the chart for clarity and use plt.show() to display
the pie chart.
This exercise focuses on creating an aesthetically pleasing and informative
pie chart, which is crucial for effective data communication in a business
setting.
【Trivia】
‣ The pie chart is one of the most commonly used charts in business and
data analytics to represent the proportional distribution of different
categories.
‣ Matplotlib, the library used in this exercise, is a widely-used plotting
library in Python and provides a vast range of tools for creating static,
animated, and interactive visualizations.
‣ While pie charts are popular, they can sometimes be misleading or hard to
read when there are too many segments or when the differences between
segments are small. In such cases, other types of charts, such as bar charts,
might be more effective.
‣ The concept of a pie chart was first introduced by William Playfair in
1801. Since then, it has become a staple in data visualization.
18. Histogram of Sentence Lengths
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst working for a publishing company. Your manager has
asked you to analyze the lengths of sentences in a new book to understand
the author's writing style.
Create a histogram of the lengths of 200 different sentences from the book.
Generate the input data within the code and ensure that the histogram is
visually appealing, emphasizing the artistic aspect of data visualization.
Your task is to write a Python script that generates the input data, processes
it, and creates a visually appealing histogram.
Ensure that the histogram includes appropriate labels, a title, and a grid for
better readability.

【Data Generation Code Example】

import random
import string
# Generate random sentences
sentences = [''.join(random.choices(string.ascii_lowercase + ' ',
k=random.randint(5, 100))) for _ in range(200)]
sentence_lengths = [len(sentence) for sentence in sentences]
【Diagram Answer】

【Code Answer】

import random
import string
import matplotlib.pyplot as plt
import numpy as np
# Generate random sentences
sentences = [''.join(random.choices(string.ascii_lowercase + ' ',
k=random.randint(5, 100))) for _ in range(200)]
sentence_lengths = [len(sentence) for sentence in sentences]
# Create histogram
plt.figure(figsize=(10, 6))
plt.hist(sentence_lengths, bins=20, color='skyblue', edgecolor='black')
plt.title('Histogram of Sentence Lengths', fontsize=15)
plt.xlabel('Sentence Length', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

The task involves creating a histogram of the lengths of 200 different


sentences to analyze an author's writing style.
The first step is to generate random sentences. This is done by creating a list
of 200 sentences, each composed of random lowercase letters and spaces,
with lengths varying between 5 and 100 characters.
The length of each sentence is then calculated and stored in a list called
sentence_lengths.
Next, the matplotlib library is used to create the histogram. The plt.hist
function is used to plot the histogram, with the number of bins set to 20 for
better granularity.
The histogram is customized with a sky-blue color, black edges for the bars,
and a grid with dashed lines for better readability.
The title, x-axis, and y-axis labels are added to make the histogram more
informative.
Finally, the plt.show function displays the histogram. This exercise
emphasizes the artistic aspect of data visualization, ensuring that the
histogram is not only informative but also visually appealing.
【Trivia】
‣ Histograms are a type of bar chart that represent the distribution of
numerical data by showing the frequency of data points within specified
ranges or bins.
‣ The choice of bin size can significantly affect the appearance and
interpretability of a histogram. Too few bins can oversimplify the data,
while too many bins can make the histogram cluttered and hard to read.
‣ Matplotlib is a widely used plotting library in Python, known for its
flexibility and extensive customization options. It is often used in
conjunction with other libraries like NumPy and pandas for data analysis
and visualization.
‣ Data visualization is a crucial skill in data science, as it helps in
understanding complex data sets and communicating insights effectively.
Visual appeal can enhance the readability and impact of the visualizations.
19. Generate a Heatmap of a 9x9 Matrix of
Random Values
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data visualization specialist working for a company that wants to
create a visually appealing heatmap to display random data.
Your task is to generate a heatmap of a 9x9 matrix of random values.
The heatmap should be visually striking and artistic.
Ensure that the code generates the random data within the script itself and
outputs the heatmap.
The goal is to focus on creating an aesthetically pleasing visual
representation using Python.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(9, 9)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(9, 9)
plt.figure(figsize=(10, 8))
sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis", cbar=True,
linewidths=.5, linecolor='white')
plt.title("Artistic Heatmap of Random Values")
plt.show()

To create an artistic heatmap of a 9x9 matrix of random values, we start by


generating the random data using NumPy.
NumPy's random.rand function creates a 9x9 array of random values
between 0 and 1.
Next, we use Matplotlib and Seaborn to visualize this data.
Seaborn's heatmap function is particularly useful for creating heatmaps with
various customization options.
We set the figure size to make the heatmap larger and more visually
appealing.
The annot=True parameter ensures that each cell's value is displayed on the
heatmap, and fmt=".2f" formats these values to two decimal places.
The cmap="viridis" parameter sets the color map to 'viridis', which is
known for its visually appealing gradient.
We also add grid lines between the cells using linewidths=.5 and
linecolor='white' to enhance the visual separation of the cells.
Finally, we add a title to the heatmap to give context to the visualization and
display the plot using plt.show().
This approach ensures that the heatmap is not only functional but also
aesthetically pleasing.
【Trivia】
‣ Heatmaps are a great way to visualize data density and patterns within a
matrix.
‣ The 'viridis' colormap is often preferred for its perceptual uniformity,
making it suitable for viewers with color vision deficiencies.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ Adding annotations to a heatmap can make it more informative,
especially when presenting data to stakeholders who may not be familiar
with the underlying data.
20. Polar Plot of Sinusoidal Functions
Importance★★★☆☆
Difficulty★★☆☆☆
You are tasked with creating a polar plot to visualize the sum of sine and
cosine functions. This plot will be used in a presentation to demonstrate
how trigonometric functions can be combined and represented in polar
coordinates, creating visually appealing and informative graphics. Your
goal is to generate the polar plot of the function r=sin⁡(θ)+cos⁡(θ)r =
\sin(\theta) + \cos(\theta)r=sin(θ)+cos(θ) over the range 0≤θ<2π0 \leq \theta
< 2\pi0≤θ<2π. The plot should be clear and aesthetically pleasing to
enhance the presentation.
【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.sin(theta) + np.cos(theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000) # # Generate 1000 points between
0 and 2π
r = np.sin(theta) + np.cos(theta) # # Calculate the r values for each theta
plt.figure(figsize=(8, 8)) # # Set the figure size
ax = plt.subplot(111, projection='polar') # # Create a polar subplot
ax.plot(theta, r, linewidth=2, color='blue') # # Plot the polar plot with
blue line and 2 width
ax.set_title(r'$r = \sin(\theta) + \cos(\theta)$', fontsize=16) # # Add a title
to the plot
plt.show() # # Display the plot

The task involves creating a polar plot to visualize the function


r=sin⁡(θ)+cos⁡(θ)r = \sin(\theta) + \cos(\theta)r=sin(θ)+cos(θ).
Polar plots are useful for representing data where the radius is a function of
the angle, often seen in trigonometric functions.
First, we generate an array of θ\thetaθ values ranging from 0 to 2π2\pi2π
using np.linspace.
This function returns evenly spaced values over the specified interval,
ensuring a smooth curve for the plot.
Next, we calculate the corresponding rrr values using the given function
r=sin⁡(θ)+cos⁡(θ)r = \sin(\theta) + \cos(\theta)r=sin(θ)+cos(θ).
The sine and cosine functions are combined to form the rrr values, which
will define the radial distance from the origin for each θ\thetaθ.
We then set up the plot using Matplotlib.
The plt.figure(figsize=(8, 8)) command creates a new figure with specified
dimensions to ensure the plot is large enough to be easily viewed.
The plt.subplot(111, projection='polar') command creates a polar subplot,
specifying that the plot should use polar coordinates.
We plot the data using ax.plot(theta, r, linewidth=2, color='blue'), which
draws the polar plot with a blue line of width 2.
The ax.set_title function adds a title to the plot, formatted in LaTeX for
clarity.
Finally, plt.show() displays the plot.
This exercise demonstrates how to create visually appealing and
informative polar plots, enhancing presentations and reports with artistic
and precise visualizations.
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system
where each point on a plane is determined by an angle and a distance from a
reference point.
‣ Polar plots are often used in engineering, physics, and navigation to
represent data that has a directional component.
‣ The combination of sine and cosine functions can produce a variety of
interesting and complex shapes when plotted in polar coordinates, such as
roses, spirals, and lemniscates.
‣ The function r=sin⁡(θ)+cos⁡(θ)r = \sin(\theta) + \cos(\theta)r=sin(θ)+cos(θ)
simplifies to r=2cos⁡(θ−π4)r = \sqrt{2}\cos(\theta - \frac{\pi}{4})r=2​
cos(θ−4π​), showing that it is a cosine function with a phase shift and a
different amplitude.
21. Artistic Network Graph Visualization with
Python
Importance★★★☆☆
Difficulty★★★★☆
A client has requested a visually appealing network graph to represent the
connections between different entities in their system.
Your task is to create a simple network graph with 20 nodes and 25 edges
using Python.
The graph should not only be functional but also emphasize artistic and
aesthetic elements.
Generate the input data within the code itself.
Please ensure that the graph is visually engaging and uses colors, shapes,
and sizes creatively to enhance its artistic appeal.
The final output should be a graph that is both informative and visually
striking.

【Data Generation Code Example】

import random
import networkx as nx
nodes = list(range(1, 21))
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(25)]
print(nodes)
print(edges)
【Diagram Answer】

【Code Answer】

import random
import networkx as nx
import matplotlib.pyplot as plt
nodes = list(range(1, 21))
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(25)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G)
plt.figure(figsize=(10, 10))
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='skyblue',
edgecolors='black')
nx.draw_networkx_edges(G, pos, width=2, alpha=0.5, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title("Artistic Network Graph", fontsize=20)
plt.show()

To create an artistic network graph in Python, we use the networkx and


matplotlib libraries.
First, we generate the nodes and edges.
We create a list of nodes numbered from 1 to 20 and generate 25 edges by
randomly pairing nodes.
Next, we initialize a graph object using networkx and add the nodes and
edges to it.
The spring_layout function is used to position the nodes in a visually
appealing manner.
We then customize the appearance of the graph by setting node sizes,
colors, and edge properties.
Finally, we use matplotlib to display the graph with a title.
This approach ensures that the graph is not only functional but also visually
engaging, fulfilling the client's request for an artistic representation.
【Trivia】
‣ The spring_layout function in networkx uses the Fruchterman-Reingold
algorithm, which positions nodes in a way that visually balances the graph.
‣ Network graphs are widely used in various fields, including social
network analysis, biology, and computer science, to represent relationships
between entities.
‣ Customizing the appearance of network graphs can significantly enhance
their readability and aesthetic appeal, making complex data more accessible
and engaging.
22. Monthly Expenses Bar Chart
Importance★★★★☆
Difficulty★★★☆☆
A financial consultancy firm has tasked you with creating a visually
appealing bar chart to compare the monthly expenses of five different
households. The data for these expenses should be generated within the
code itself. Your goal is to create a chart that is not only informative but
also visually artistic. Ensure the chart includes labels, a title, and a legend.
The households are labeled as Household A, Household B, Household C,
Household D, and Household E. The expenses should be broken down into
categories such as Rent, Groceries, Utilities, Transportation, and
Miscellaneous.
【Data Generation Code Example】

import matplotlib.pyplot as plt


households = ['Household A', 'Household B', 'Household C', 'Household
D', 'Household E']
categories = ['Rent', 'Groceries', 'Utilities', 'Transportation',
'Miscellaneous']
expenses = [[1200, 300, 150, 100, 200], [1300, 350, 160, 120, 220],
[1250, 320, 140, 110, 210], [1400, 400, 170, 130, 230], [1350, 370, 155,
115, 225]]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


households = ['Household A', 'Household B', 'Household C', 'Household
D', 'Household E']
categories = ['Rent', 'Groceries', 'Utilities', 'Transportation',
'Miscellaneous']
expenses = [[1200, 300, 150, 100, 200], [1300, 350, 160, 120, 220],
[1250, 320, 140, 110, 210], [1400, 400, 170, 130, 230], [1350, 370, 155,
115, 225]]
## Transpose the expenses list to get expenses per category
expenses_per_category = list(map(list, zip(*expenses)))
## Define the position of bars on the X-axis
bar_width = 0.15
r1 = range(len(households))
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
r4 = [x + bar_width for x in r3]
r5 = [x + bar_width for x in r4]
## Create the bar chart
plt.figure(figsize=(10, 6))
plt.bar(r1, expenses_per_category, color='b', width=bar_width,
edgecolor='grey', label='Rent')
plt.bar(r2, expenses_per_category, color='g', width=bar_width,
edgecolor='grey', label='Groceries')
plt.bar(r3, expenses_per_category, color='r', width=bar_width,
edgecolor='grey', label='Utilities')
plt.bar(r4, expenses_per_category, color='c', width=bar_width,
edgecolor='grey', label='Transportation')
plt.bar(r5, expenses_per_category, color='m', width=bar_width,
edgecolor='grey', label='Miscellaneous')
## Add labels and title
plt.xlabel('Households', fontweight='bold')
plt.ylabel('Expenses ($)', fontweight='bold')
plt.xticks([r + 2*bar_width for r in range(len(households))], households)
plt.title('Monthly Expenses of 5 Households', fontweight='bold')
plt.legend()
## Display the chart
plt.show()

This exercise involves creating a bar chart to compare the monthly expenses
of five households.
First, the necessary libraries are imported, specifically matplotlib.pyplot for
plotting. The data for the households and their expenses across different
categories is generated within the code to ensure reproducibility.
The expenses data is structured as a list of lists, where each sublist
corresponds to the expenses for a particular household. This data is then
transposed to make it easier to plot expenses per category.
The positions for the bars on the X-axis are calculated, ensuring that each
category is placed next to the others for each household. The bar chart is
then created using different colors for each expense category to enhance
visual distinction.
Labels, a title, and a legend are added to the chart to improve readability
and provide context. The plt.show() function is called to display the chart.
The use of colors, labels, and the layout of the bars are designed to make
the chart both informative and visually appealing, adhering to the goal of
creating an artistic visualization.
【Trivia】
‣ The matplotlib library is one of the most widely used plotting libraries in
Python, known for its versatility and ease of use.
‣ Creating visually appealing charts is not just about aesthetics; it helps in
better understanding and interpreting data.
‣ When designing charts, it’s important to consider colorblind-friendly
palettes to ensure accessibility for all users.
‣ The concept of "data ink ratio" introduced by Edward Tufte emphasizes
minimizing non-essential ink in charts to focus on the data itself. This
principle can guide the design of more effective visualizations.
23. Scatter Plot Art with Python
Importance★★★☆☆
Difficulty★★★☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to display on their website. They need a scatter plot with 600 points, each
point having different colors and sizes to create a stunning visual effect.
The data for the scatter plot should be generated within the code itself. Your
task is to write a Python script that generates this scatter plot and ensures it
is artistically appealing.
【Data Generation Code Example】

import numpy as np
np.random.seed(0)
x = np.random.rand(600)
y = np.random.rand(600)
colors = np.random.rand(600)
sizes = 1000 * np.random.rand(600)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(600)
y = np.random.rand(600)
colors = np.random.rand(600)
sizes = 1000 * np.random.rand(600)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create an artistic scatter plot in Python, we use the matplotlib library,


which is a powerful tool for creating various types of plots and
visualizations.
First, we import the necessary libraries: numpy for generating random data
and matplotlib.pyplot for plotting.
We set a random seed using np.random.seed(0) to ensure reproducibility of
the random numbers.
Next, we generate 600 random points for the x and y coordinates using
np.random.rand(600), which creates an array of 600 numbers between 0 and
1.
We also generate random colors for each point with np.random.rand(600)
and random sizes with 1000 * np.random.rand(600), scaling the sizes to
make them more visually appealing.
The plt.scatter function is used to create the scatter plot, where x and y are
the coordinates, c=colors sets the colors, s=sizes sets the sizes, alpha=0.5
makes the points semi-transparent, and cmap='viridis' applies a colormap.
We add a color bar with plt.colorbar() to show the color scale.
Finally, we set the title and labels for the axes with plt.title, plt.xlabel, and
plt.ylabel, and display the plot with plt.show().
This approach ensures that the scatter plot is not only functional but also
artistically pleasing, making it suitable for display in an art gallery.
【Trivia】
‣ The matplotlib library is one of the most widely used plotting libraries in
Python and is highly customizable for creating complex visualizations.
‣ The cmap parameter in plt.scatter allows you to choose from a variety of
colormaps, each providing a different aesthetic effect.
‣ Using alpha to adjust the transparency of points can help in visualizing
dense plots by reducing overlap and making the plot more readable.
‣ The np.random.seed function is crucial for creating reproducible results,
especially when generating random data for visualizations or simulations.
24. Pie Chart of Flower Distribution
Importance★★★☆☆
Difficulty★★☆☆☆
A client has a garden with various types of flowers and wants to visualize
the distribution of these flowers in a pie chart. You need to create a visually
appealing pie chart using Python to represent this distribution.
Generate the following sample data within your code:
Roses: 30
Tulips: 20
Daisies: 25
Sunflowers: 15
Lilies: 10
Use this data to create a pie chart that emphasizes artistic and aesthetic
aspects. Ensure the chart is visually appealing with appropriate colors,
labels, and a title.

【Data Generation Code Example】

flowers = ['Roses', 'Tulips', 'Daisies', 'Sunflowers', 'Lilies']

counts = [30, 20, 25, 15, 10]


【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


flowers = ['Roses', 'Tulips', 'Daisies', 'Sunflowers', 'Lilies']
counts = [30, 20, 25, 15, 10]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']
plt.figure(figsize=(10, 7))
plt.pie(counts, labels=flowers, colors=colors, autopct='%1.1f%%',
startangle=140, pctdistance=0.85, wedgeprops={'edgecolor': 'black'})
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.title('Distribution of Different Types of Flowers in the Garden',
fontsize=14)
plt.axis('equal')
plt.tight_layout()
plt.show()

To create a visually appealing pie chart, we first import the


matplotlib.pyplot library.
We define the flower types and their respective counts as lists.
Next, we choose a set of colors to differentiate between the flower types.
We create a pie chart using the plt.pie function, specifying the counts,
labels, colors, and other aesthetic parameters such as autopct for percentage
display, startangle for the initial angle, and pctdistance for the distance of
the percentage labels from the center.
To enhance the visual appeal, we add a white circle in the center to create a
donut-like appearance using plt.Circle and fig.gca().add_artist.
We set the title of the chart and ensure the pie chart is drawn as a circle
using plt.axis('equal').
Finally, we use plt.tight_layout to adjust the layout and plt.show to display
the chart.
【Trivia】
‣ The pie chart was invented by William Playfair in 1801.
‣ Pie charts are best used for displaying proportional data and percentages.
‣ It's generally recommended to limit the number of slices in a pie chart to
make it easier to read and interpret.
‣ The donut chart, a variation of the pie chart with a hole in the center, can
help focus the viewer's attention on the data distribution.
25. Plant Height Histogram Visualization
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst working for a botanical research company. Your task
is to create a visually appealing histogram to display the heights of 200
different plants. The histogram should not only provide an accurate
representation of the data but also be aesthetically pleasing to engage your
audience.
Use Python to generate the data and create the histogram. Ensure that the
histogram includes labels and a title to enhance its visual appeal.

【Data Generation Code Example】

import numpy as np
# Generate random heights for 200 plants
heights = np.random.normal(loc=150, scale=30, size=200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
# Generate random heights for 200 plants
heights = np.random.normal(loc=150, scale=30, size=200)
# Create the histogram
plt.figure(figsize=(10, 6))
plt.hist(heights, bins=20, color='skyblue', edgecolor='black')
# Add title and labels
plt.title('Distribution of Plant Heights', fontsize=15)
plt.xlabel('Height (cm)', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
# Enhance the visual appeal
plt.grid(True, linestyle='--', alpha=0.7)
plt.axvline(np.mean(heights), color='red', linestyle='dashed', linewidth=1,
label='Mean Height')
plt.legend()
# Display the plot
plt.show()

In this exercise, the primary focus is on creating a visually appealing


histogram to display the distribution of plant heights using Python. The
histogram is a powerful tool for visualizing the frequency distribution of a
dataset, and by making it aesthetically pleasing, you can engage your
audience more effectively.
First, we use the numpy library to generate random data representing the
heights of 200 plants. The np.random.normal function is used to create a
normal distribution of heights with a mean (loc) of 150 cm and a standard
deviation (scale) of 30 cm.
Next, we use the matplotlib.pyplot library to create the histogram. The
plt.hist function is used to plot the data, with the bins parameter set to 20 to
control the number of bins in the histogram. The color and edgecolor
parameters are used to enhance the visual appeal of the bars.
We then add a title and labels to the histogram using plt.title, plt.xlabel, and
plt.ylabel to provide context and make the plot more informative. To further
enhance the visual appeal, we add a grid to the plot using plt.grid, and we
draw a vertical line representing the mean height using plt.axvline. The
plt.legend function is used to add a legend to the plot.
Finally, the plt.show function is called to display the histogram. This
approach ensures that the histogram is not only informative but also
visually engaging, making it easier for the audience to interpret the data.
【Trivia】
‣ Histograms are a type of bar chart that represent the frequency
distribution of a dataset.
‣ The choice of the number of bins in a histogram can significantly affect
the interpretation of the data.
‣ Matplotlib is one of the most widely used libraries for data visualization
in Python, offering a wide range of customization options to enhance the
visual appeal of plots.
‣ Aesthetically pleasing visualizations can improve data comprehension
and retention, making them a valuable tool in data analysis and
presentation.
26. Box Plot of Animal Weights
Importance★★★☆☆
Difficulty★★★☆☆
You are a data analyst working for a wildlife research organization. The
organization has collected the weights of 50 different animals and wants to
visualize the distribution of these weights using a box plot. Your task is to
generate a Python script that creates this box plot. The goal of this exercise
is to emphasize the artistic and visual appeal of the plot, making it not only
informative but also aesthetically pleasing.
Use the following code to generate the sample data for the weights of the 50
animals:

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
weights = np.random.normal(50, 15, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
weights = np.random.normal(50, 15, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(weights, patch_artist=True,
boxprops=dict(facecolor='skyblue', color='blue'),
whiskerprops=dict(color='blue'),
capprops=dict(color='blue'),
medianprops=dict(color='red'),
flierprops=dict(marker='o', color='red', alpha=0.5))
plt.title('Distribution of Animal Weights', fontsize=15, fontweight='bold')
plt.ylabel('Weight (kg)', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create a visually appealing box plot of the animal weights, we start by


importing the necessary libraries: numpy for generating the sample data and
matplotlib.pyplot for plotting. The sample data is generated using a normal
distribution with a mean of 50 and a standard deviation of 15, ensuring
reproducibility with np.random.seed(0).
▸ The plt.figure function sets the size of the figure to 10 by 6 inches,
providing a spacious canvas for the plot. The plt.boxplot function is used to
create the box plot, with several customization options to enhance its visual
appeal:
‣ patch_artist=True fills the box with color.
‣ boxprops sets the properties of the box, including the face color and edge
color.
‣ whiskerprops, capprops, and medianprops customize the appearance of
the whiskers, caps, and median line, respectively.
‣ flierprops customizes the appearance of outliers, making them red circles
with some transparency.
The title and y-axis label are added with plt.title and plt.ylabel, using larger
fonts and bold text for better readability. Finally, plt.grid adds a grid to the
background with dashed lines and slight transparency, enhancing the overall
aesthetics.
This approach ensures that the box plot is not only informative but also
visually engaging, making it suitable for presentations and reports.
【Trivia】
Box plots, also known as whisker plots, were introduced by John Tukey in
1970 as a way to graphically depict groups of numerical data through their
quartiles. They are particularly useful for identifying outliers and
understanding the spread and skewness of the data. The median line within
the box represents the second quartile (Q2), while the edges of the box
represent the first (Q1) and third (Q3) quartiles. The whiskers extend to the
smallest and largest values within 1.5 times the interquartile range (IQR)
from the quartiles, and any points outside this range are considered outliers.
27. Heatmap of a 10x10 Matrix of Random Values
Importance★★★☆☆
Difficulty★★☆☆☆
You are tasked with creating a visually appealing heatmap of a 10x10
matrix filled with random values. This heatmap should not only display the
data but also be aesthetically pleasing, focusing on the artistic aspect of data
visualization. The heatmap should be generated using Python.
Generate the random data within your code and ensure the heatmap is
colorful and well-labeled.

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
data = np.random.rand(10, 10)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(0)
data = np.random.rand(10, 10)
plt.figure(figsize=(10, 8))
sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis", cbar=True,
linewidths=.5, linecolor='black')
plt.title('Heatmap of 10x10 Matrix of Random Values', fontsize=20)
plt.xlabel('X-axis', fontsize=15)
plt.ylabel('Y-axis', fontsize=15)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.show()

To create a visually appealing heatmap, we start by importing necessary


libraries: numpy for generating random data, and matplotlib and seaborn for
visualization.
We set a random seed using np.random.seed(0) to ensure reproducibility.
The data is generated using np.random.rand(10, 10), which creates a 10x10
matrix of random values between 0 and 1.
For the heatmap, we use seaborn's heatmap function. We set annot=True to
display the values in each cell and fmt=".2f" to format the numbers to two
decimal places. The cmap="viridis" parameter is chosen for its appealing
color gradient. We add a color bar with cbar=True and set linewidths=.5 and
linecolor='black' to add grid lines for better visual separation of cells.
The plot is further enhanced by setting the figure size to 10x8 inches and
adding titles and axis labels with appropriate font sizes. Finally, plt.show()
displays the heatmap. The goal is not only to present data but to do so in an
artistically pleasing manner, making the visualization both functional and
beautiful.
【Trivia】
‣ Seaborn is built on top of matplotlib and provides a high-level interface
for drawing attractive statistical graphics.
‣ The "viridis" colormap used in this example is designed to be
perceptually uniform, meaning it is easy to interpret by those with color
vision deficiencies.
‣ Heatmaps are a great way to visualize matrix-like data and can be used in
various fields such as biology, finance, and machine learning to identify
patterns and correlations.
28. 3D Surface Plot Art with Python
Importance★★★☆☆
Difficulty★★★☆☆
A client in the art industry wants to create a visually appealing 3D surface
plot to showcase the function z=exp⁡(x)⋅sin⁡(y)z=\exp(x)\cdot
\sin(y)z=exp(x)⋅sin(y). They need a Python script that not only generates
the plot but also emphasizes artistic elements to make the visualization
stand out.
Write a Python script that generates a 3D surface plot of the function
z=exp⁡(x)⋅sin⁡(y)z=\exp(x)\cdot \sin(y)z=exp(x)⋅sin(y) over the range xxx
from -2 to 2 and yyy from 0 to 2π2\pi 2π. The plot should be visually
appealing, with artistic elements such as customized colors, lighting, and
labels.
Ensure the script generates the data within the code itself and produces the
plot when executed.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-2, 2, 100)
y = np.linspace(0, 2 * np.pi, 100)
x, y = np.meshgrid(x, y)
z = np.exp(x) * np.sin(y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
x = np.linspace(-2, 2, 100)
y = np.linspace(0, 2 * np.pi, 100)
x, y = np.meshgrid(x, y)
z = np.exp(x) * np.sin(y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap=cm.viridis, edgecolor='none')
ax.set_title('3D Surface Plot of $z = e^x \cdot \sin(y)$')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
plt.show()

To create a visually appealing 3D surface plot of the function


z=exp⁡(x)⋅sin⁡(y)z=\exp(x)\cdot \sin(y)z=exp(x)⋅sin(y), we use Python's
matplotlib library.
First, we import the necessary libraries: numpy for numerical operations,
matplotlib.pyplot for plotting, and mpl_toolkits.mplot3d for 3D plotting
capabilities. We also import cm from matplotlib for colormap
functionalities.
Next, we generate the data. We create a range of values for xxx from -2 to 2
and for yyy from 0 to 2π2\pi 2π. We use np.meshgrid to create a grid of xxx
and yyy values, and then compute zzz using the given function
z=exp⁡(x)⋅sin⁡(y)z=\exp(x)\cdot \sin(y)z=exp(x)⋅sin(y).
We then create a figure and a 3D subplot. Using ax.plot_surface, we plot the
surface with the viridis colormap to enhance the visual appeal. We set the
title and labels for the axes to provide context.
Finally, we add a color bar to the plot for reference and display the plot
using plt.show(). This script ensures that the plot is not only informative but
also visually engaging, making it suitable for artistic presentations.
【Trivia】
‣ The viridis colormap is often used for its perceptual uniformity, meaning
it is visually appealing and interpretable by those with color vision
deficiencies.
‣ The function z=exp⁡(x)⋅sin⁡(y)z=\exp(x)\cdot \sin(y)z=exp(x)⋅sin(y)
combines exponential growth with sinusoidal oscillations, creating an
interesting and complex surface.
‣ 3D surface plots are commonly used in various fields, including
engineering, physics, and finance, to visualize complex functions and data
sets.
29. Polar Plot of the Function r = θ^2
Importance★★★☆☆
Difficulty★★★☆☆
A client has requested a visually appealing representation of the
mathematical function r = θ^2 in a polar plot.
Your task is to create a Python script that generates this plot.
The plot should be artistically enhanced to be visually engaging.
Ensure that the plot is clear and aesthetically pleasing.
You will need to generate the input data within the script.
The final output should be a polar plot of the function r = θ^2.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 500)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 500)
r = theta ** 2
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='purple', linewidth=2)
ax.set_title("Polar Plot of r = θ^2", va='bottom')
ax.grid(True)
plt.show()

To create a visually appealing polar plot of the function r = θ^2, we start by


importing the necessary libraries: numpy for numerical operations and
matplotlib for plotting.
We generate the data for θ using numpy's linspace function, which creates
an array of 500 values evenly spaced between 0 and 2π. This range ensures
that we cover a full circle in the polar coordinate system.
Next, we calculate the corresponding r values by squaring each θ value.
This is done using the expression r = θ^2.
To create the plot, we set up a figure with a size of 8x8 inches for better
visibility and aesthetics. We then create a polar subplot using plt.subplot
with the 'polar' projection.
The plot is drawn using the ax.plot function, where we specify the θ and r
values. We choose a purple color and set the line width to 2 to make the plot
visually striking.
We add a title to the plot using ax.set_title, positioning it at the bottom for a
better visual effect. Finally, we enable the grid for better readability using
ax.grid(True).
The plt.show function is called to display the plot. This script ensures that
the plot is not only accurate but also visually engaging, meeting the client's
request for an artistically enhanced representation.
【Trivia】
‣ Polar plots are particularly useful for representing data that has a
directional component.
‣ The polar coordinate system is used in many fields, including physics,
engineering, and navigation.
‣ The function r = θ^2 is an example of a spiral, specifically an
Archimedean spiral, which has many applications in antenna theory and
other areas of science and engineering.
30. Simple Network Graph Visualization
Importance★★★☆☆
Difficulty★★☆☆☆
A client has requested a visual representation of a simple network graph for
their presentation. The graph should consist of 25 nodes and 30 edges, and
it should be visually appealing to capture the audience's attention. The goal
is to create a piece of visual art using Python that not only represents the
network but also emphasizes aesthetics.
Please write a Python script to generate and display this network graph. The
script should create the input data (nodes and edges) within the code itself.
Make sure the graph is visually attractive, using colors, sizes, and other
graphical elements to enhance its artistic appeal.

【Data Generation Code Example】

import networkx as nx
import matplotlib.pyplot as plt
import random
G = nx.Graph()
# Create 25 nodes
nodes = [i for i in range(25)]
G.add_nodes_from(nodes)
# Create 30 edges
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(30)]
G.add_edges_from(edges)
【Diagram Answer】

【Code Answer】

import networkx as nx
import matplotlib.pyplot as plt
import random
G = nx.Graph()
# Create 25 nodes
nodes = [i for i in range(25)]
G.add_nodes_from(nodes)
# Create 30 edges
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(30)]
G.add_edges_from(edges)
# Draw the network graph with artistic enhancements
pos = nx.spring_layout(G)
plt.figure(figsize=(12, 12))
# Draw nodes with varying sizes and colors
node_sizes = [random.randint(100, 1000) for _ in range(25)]
node_colors = [plt.cm.viridis(random.random()) for _ in range(25)]
nx.draw_networkx_nodes(G, pos, node_size=node_sizes,
node_color=node_colors, alpha=0.8)
# Draw edges with varying thicknesses
edge_widths = [random.uniform(0.5, 3) for _ in range(len(G.edges()))]
nx.draw_networkx_edges(G, pos, width=edge_widths, alpha=0.6)
# Draw labels
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title("Artistic Network Graph", fontsize=20)
plt.axis('off')
plt.show()

This exercise focuses on creating a visually appealing network graph using


Python.
The script begins by importing necessary libraries: networkx for creating
and manipulating the graph, matplotlib.pyplot for plotting, and random for
generating random data.
The graph G is initialized as an empty graph. 25 nodes are added using a
list comprehension, creating a list of integers from 0 to 24. These nodes are
then added to the graph.
Next, 30 edges are created. Each edge is a tuple of two randomly chosen
nodes from the list of nodes. These edges are added to the graph.
The spring_layout function is used to position the nodes in a visually
pleasing manner. The figure function sets the size of the plot.
Nodes are drawn with varying sizes and colors to enhance the visual appeal.
Node sizes are randomly chosen between 100 and 1000, and colors are
randomly selected from the viridis colormap. The draw_networkx_nodes
function is used to draw the nodes with these attributes.
Edges are drawn with varying thicknesses, randomly chosen between 0.5
and 3. The draw_networkx_edges function is used to draw the edges with
these attributes.
Labels are added to the nodes using the draw_networkx_labels function,
with a font size of 12 and black color.
Finally, a title is added to the plot, the axis is turned off, and the plot is
displayed using the show function.
This approach ensures that the network graph is not only functional but also
visually engaging, making it suitable for presentations and artistic purposes.
【Trivia】
‣ The spring_layout function in NetworkX uses the Fruchterman-Reingold
force-directed algorithm, which positions nodes in a way that visually
balances the graph.
‣ The viridis colormap is designed to be perceptually uniform, meaning it
looks good and is easy to interpret for viewers with color vision
deficiencies.
‣ Network graphs are widely used in various fields, including social
network analysis, biology (e.g., protein interaction networks), and computer
science (e.g., network topology).
‣ The aesthetics of data visualization can significantly impact the
effectiveness of communication, making it crucial to balance functionality
and visual appeal.
31. Scatter Plot Visual Art in Python
Importance★★★☆☆
Difficulty★★★☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to showcase in their upcoming digital art exhibition. They need a scatter
plot with 700 points, where each point has a different color and size to
enhance the visual aesthetics.
Generate the data within the code itself and ensure the plot is artistically
engaging. Use Python to create this scatter plot and make sure it is both
colorful and varied in size.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(700)
y = np.random.rand(700)
colors = np.random.rand(700)
area = (30 * np.random.rand(700))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(700)
y = np.random.rand(700)
colors = np.random.rand(700)
area = (30 * np.random.rand(700))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Artistic Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()

To create an artistically engaging scatter plot in Python, we use the


matplotlib library, which is widely known for its extensive plotting
capabilities.
First, we import the necessary libraries: numpy for generating random data
and matplotlib.pyplot for plotting. Setting the random seed ensures that the
random numbers generated are reproducible.
We generate 700 random points for the x and y coordinates using
np.random.rand(700). Each point's color is also randomly assigned using
np.random.rand(700). The size of each point is determined by area,
calculated as the square of random values scaled by 30. This scaling ensures
a variety of point sizes, enhancing the visual appeal.
The plt.scatter function is used to create the scatter plot. The alpha
parameter is set to 0.5 to make the points semi-transparent, adding to the
artistic effect. Titles and labels for the axes are added to provide context.
Finally, plt.show() displays the plot.
This exercise emphasizes the creation of visually appealing plots,
combining randomness with artistic elements to produce a unique visual
experience.
【Trivia】
‣ The matplotlib library was originally developed by John D. Hunter in
2003. It has since become one of the most popular plotting libraries in
Python.
‣ Scatter plots are commonly used in data science to visualize the
relationship between two variables, but they can also be used creatively in
digital art.
‣ The transparency effect (alpha parameter) in matplotlib can be
particularly useful in creating layered visual effects, often seen in modern
digital art.
32. Zoo Animal Distribution Pie Chart
Importance★★★☆☆
Difficulty★★★☆☆
You are a data analyst working for a zoo, and you have been asked to create
a visual representation of the distribution of different types of animals in the
zoo.
Your goal is to create a pie chart that shows the proportion of various
animal types.
The data for the animal types and their counts should be generated within
the code.
Ensure that the pie chart is not only informative but also visually appealing,
emphasizing the artistic aspect of data visualization.

【Data Generation Code Example】

import matplotlib.pyplot as plt


animal_types = ['Mammals', 'Birds', 'Reptiles', 'Amphibians', 'Fish']
counts = [50, 30, 10, 5, 5]
plt.pie(counts, labels=animal_types, autopct='%1.1f%%', startangle=140)
plt.axis('equal')
plt.title('Distribution of Different Types of Animals in the Zoo')
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


animal_types = ['Mammals', 'Birds', 'Reptiles', 'Amphibians', 'Fish']
counts = [50, 30, 10, 5, 5]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']
explode = (0.1, 0, 0, 0, 0) # explode the 1st slice (Mammals)
plt.pie(counts, explode=explode, labels=animal_types, colors=colors,
autopct='%1.1f%%', startangle=140, shadow=True)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Distribution of Different Types of Animals in the Zoo')
plt.show()

To create a visually appealing pie chart representing the distribution of


different types of animals in a zoo, we use the Matplotlib library in Python.
First, we import the Matplotlib library using import matplotlib.pyplot as plt.
Next, we define two lists: animal_types and counts.
The animal_types list contains the categories of animals (Mammals, Birds,
Reptiles, Amphibians, and Fish), and the counts list contains the
corresponding number of animals in each category.
For the pie chart to be visually appealing, we add colors and an explode
effect.
The colors list specifies custom colors for each slice of the pie chart.
The explode tuple is used to "explode" or offset the first slice (Mammals)
for emphasis.
We then create the pie chart using plt.pie().
The autopct='%1.1f%%' argument displays the percentage value on each
slice, and startangle=140 rotates the start of the pie chart for better visual
balance.
The shadow=True argument adds a shadow effect to the pie chart for a 3D
look.
The plt.axis('equal') function ensures that the pie chart is drawn as a circle.
Finally, we set the title of the chart using plt.title() and display the chart
with plt.show().
This approach not only provides a clear representation of the data but also
emphasizes the artistic aspect of data visualization by using colors,
shadows, and an exploded slice.
【Trivia】
‣ The pie chart was first introduced by William Playfair in 1801.
‣ Matplotlib is a widely used library for creating static, animated, and
interactive visualizations in Python.
‣ The explode parameter in Matplotlib's pie function is useful for
highlighting a particular slice of the pie chart.
‣ Using custom colors and shadows can significantly enhance the visual
appeal of a pie chart.
‣ Pie charts are best used for displaying data with a small number of
categories to avoid clutter and maintain readability.
33. Histogram of Vehicle Speeds
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst at a transportation company. The company has
collected speed data from 200 different vehicles over the past month. Your
task is to create a visually appealing histogram of these speeds using
Python. The histogram should not only display the data but also be
artistically pleasing.
Create the speed data within your code. The data should be normally
distributed with a mean of 60 km/h and a standard deviation of 10 km/h.
Ensure that the histogram is visually engaging and includes appropriate
labels and titles.

【Data Generation Code Example】

import numpy as np
speeds = np.random.normal(60, 10, 200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
speeds = np.random.normal(60, 10, 200)
plt.figure(figsize=(10, 6))
sns.histplot(speeds, bins=20, kde=True, color='skyblue',
edgecolor='black')
plt.title('Histogram of Vehicle Speeds', fontsize=20, fontweight='bold')
plt.xlabel('Speed (km/h)', fontsize=15)
plt.ylabel('Frequency', fontsize=15)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

In this exercise, we aim to create a visually engaging histogram of vehicle


speeds using Python.
The data is generated to simulate the speeds of 200 vehicles, following a
normal distribution with a mean of 60 km/h and a standard deviation of 10
km/h.
We use the numpy library to generate this data.
To create the histogram, we use the matplotlib and seaborn libraries.
matplotlib is a powerful plotting library, and seaborn builds on it to provide
a high-level interface for drawing attractive statistical graphics.
First, we set the figure size to make the plot larger and more readable.
We then use seaborn.histplot to create the histogram, specifying the number
of bins and enabling the kernel density estimate (KDE) to add a smooth
curve over the histogram.
We choose a sky-blue color for the bars and add black edges to make them
stand out.
We enhance the plot by adding a title and labels for the x and y axes, using
larger fonts and bold text for better readability.
Finally, we add a grid with dashed lines and some transparency to make the
plot easier to interpret.
This approach not only creates a functional histogram but also ensures that
it is visually appealing, aligning with the artistic focus of this exercise.
【Trivia】
‣ The normal distribution, also known as the Gaussian distribution, is a
common continuous probability distribution.
‣ It is characterized by its bell-shaped curve, where most of the data points
are concentrated around the mean.
‣ In data visualization, adding a KDE (Kernel Density Estimate) helps to
smooth out the histogram and provide a clearer view of the data
distribution.
34. Box Plot of River Lengths
Importance★★★☆☆
Difficulty★★☆☆☆
A client working in environmental research needs to visualize the
distribution of the lengths of 50 different rivers to better understand their
data.
Your task is to create a box plot of the river lengths using Python.
Generate the data within your code and ensure the visualization is
artistically appealing.
The primary goal is to focus on the visual artistry of the plot.

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
river_lengths = np.random.randint(50, 1000, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
river_lengths = np.random.randint(50, 1000, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(river_lengths, patch_artist=True,
boxprops=dict(facecolor='lightblue', color='blue'),
whiskerprops=dict(color='blue'), capprops=dict(color='blue'),
medianprops=dict(color='red'))
plt.title('Distribution of River Lengths', fontsize=16)
plt.xlabel('Rivers', fontsize=14)
plt.ylabel('Length (km)', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create a visually appealing box plot of river lengths, we start by


importing necessary libraries: numpy for data generation and
matplotlib.pyplot for plotting.
We set a random seed for reproducibility and generate 50 random river
lengths between 50 and 1000 kilometers using np.random.randint().
We then create a figure with specific dimensions using plt.figure().
The plt.boxplot() function is used to create the box plot, with various
properties set to enhance the visual appeal: patch_artist=True enables
custom box colors, boxprops, whiskerprops, capprops, and medianprops are
dictionaries that customize the colors of the box, whiskers, caps, and
median line, respectively.
The plot is given a title and labeled axes with plt.title(), plt.xlabel(), and
plt.ylabel().
A grid is added for better readability using plt.grid().
Finally, plt.show() displays the plot.
【Trivia】
‣ Box plots are also known as box-and-whisker plots and were first
introduced by John Tukey in 1977.
‣ They are particularly useful for identifying outliers and understanding the
spread and skewness of data.
‣ The box represents the interquartile range (IQR), which contains the
middle 50% of the data, while the line inside the box represents the median.
‣ The whiskers extend to the smallest and largest values within 1.5 times
the IQR from the lower and upper quartiles, respectively.
35. Heatmap Visualization of Random Values
Importance★★★☆☆
Difficulty★★★☆☆
You are a data visualization artist working for a design firm. Your client has
requested an artistic heatmap that showcases the beauty of randomness.
Create a Python script that generates an 11x11 matrix of random values and
visualizes it as a heatmap. The heatmap should be visually appealing and
artistic, using a colormap that emphasizes the randomness.
Ensure that the script generates the random data within the code itself and
does not rely on any external data sources.
Your final output should be a heatmap that is both functional and visually
striking.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(11, 11)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(11, 11)
plt.figure(figsize=(10, 8))
sns.heatmap(data, cmap='viridis', annot=True, fmt=".2f", linewidths=.5,
cbar=True)
plt.title('Artistic Heatmap of Random Values')
plt.show()

To create an artistic heatmap of an 11x11 matrix of random values, we start


by generating the random data using NumPy's rand function, which creates
an array of the given shape filled with random values between 0 and 1.
Next, we use Matplotlib and Seaborn to visualize this data. Matplotlib is a
comprehensive library for creating static, animated, and interactive
visualizations in Python, while Seaborn is a data visualization library based
on Matplotlib that provides a high-level interface for drawing attractive and
informative statistical graphics.
We first import the necessary libraries: NumPy for data generation,
Matplotlib for plotting, and Seaborn for creating the heatmap.
We then generate the 11x11 matrix of random values.
Using plt.figure, we set the figure size to make the plot large and clear.
The sns.heatmap function is used to create the heatmap. We pass the
random data to it and choose the 'viridis' colormap, which is known for its
visually appealing gradient. The annot parameter is set to True to display
the data values in the cells, and fmt=".2f" ensures the values are shown with
two decimal places. The linewidths parameter adds space between the cells,
and cbar=True includes a color bar to the right of the heatmap.
Finally, we add a title to the heatmap using plt.title and display the plot with
plt.show.
This process results in a visually striking heatmap that emphasizes the
randomness of the data through its artistic representation.
【Trivia】
‣ The 'viridis' colormap used in this example is one of the perceptually
uniform colormaps introduced in Matplotlib 2.0. It is designed to be easy to
interpret by individuals with color vision deficiencies.
‣ Seaborn's heatmap function provides several parameters to customize the
appearance of the heatmap, including cmap for colormap, annot for
annotations, and linewidths for cell borders. These options allow for a high
degree of customization, making it a powerful tool for creating visually
appealing plots.
‣ Heatmaps are commonly used in various fields such as biology (e.g., gene
expression data), finance (e.g., correlation matrices), and geography (e.g.,
population density maps) to visualize complex data in an intuitive and
accessible way.
36. 3D Surface Plot of z = sin(x) * cos(y)
Importance★★★☆☆
Difficulty★★★☆☆
You are tasked with creating a 3D surface plot to visualize the function
z=sin⁡(x)⋅cos⁡(y)z=\sin(x)\cdot \cos(y)z=sin(x)⋅cos(y). This plot should be
aesthetically pleasing and demonstrate the artistic capabilities of Python's
visualization libraries. Your goal is to produce a visually stunning plot that
emphasizes the artistic side of data visualization. Generate the input data
within the code itself.
【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.cos(y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.cos(y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
ax.set_title('3D Surface Plot of z = sin(x) * cos(y)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

To create a visually appealing 3D surface plot of the function


z=sin⁡(x)⋅cos⁡(y)z=\sin(x)\cdot \cos(y)z=sin(x)⋅cos(y), we start by importing
necessary libraries: NumPy for numerical operations and Matplotlib for
plotting.
First, we generate a grid of x and y values using np.linspace to create 100
points between -5 and 5 for both x and y. We then use np.meshgrid to create
a 2D grid of x and y values. The function z=sin⁡(x)⋅cos⁡(y)z=\sin(x)\cdot
\cos(y)z=sin(x)⋅cos(y) is computed over this grid.
Next, we create a figure and a 3D axis using Matplotlib's figure and
add_subplot methods. The surface plot is generated using plot_surface, with
a colormap 'viridis' to enhance the visual appeal. Finally, we set the title and
labels for the axes to ensure the plot is informative and aesthetically
pleasing. The plt.show() function is called to display the plot.
This exercise highlights the artistic capabilities of Python's visualization
tools, emphasizing the importance of aesthetics in data visualization. By
carefully choosing colormaps and setting appropriate labels, we can create
plots that are not only informative but also visually engaging.
【Trivia】
‣ The viridis colormap is often preferred for its perceptual uniformity,
meaning it is visually appealing and interpretable by those with color vision
deficiencies.
‣ The plot_surface function in Matplotlib allows for extensive
customization, including lighting effects and transparency, which can
further enhance the visual appeal of 3D plots.
‣ Python's Matplotlib library is highly versatile and can be used to create a
wide range of plots, from simple 2D line plots to complex 3D
visualizations, making it a powerful tool for both data analysis and artistic
expression.
37. Polar Plot of r = 1 + cos(2θ)
Importance★★★☆☆
Difficulty★★★☆☆
You are a data visualization specialist working for an art gallery. The
gallery is hosting an exhibition on mathematical art and has tasked you with
creating a visually appealing polar plot of the function
r=1+cos⁡(2θ)r=1+\cos(2\theta)r=1+cos(2θ). The plot should not only be
accurate but also aesthetically pleasing to attract visitors. Use Python to
generate this plot and ensure that the visual aspects are given high priority.
【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 + np.cos(2 * theta)
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='purple', linewidth=2)
ax.set_title('Polar Plot of r = 1 + cos(2θ)', fontsize=15, color='navy')
ax.grid(True, color='gray', linestyle='--', linewidth=0.5)
plt.show()

To create a visually appealing polar plot of the function


r=1+cos⁡(2θ)r=1+\cos(2\theta)r=1+cos(2θ), we start by importing the
necessary libraries: numpy for numerical operations and matplotlib for
plotting.
We generate an array of θ\theta θ values ranging from 0 to 2π2\pi 2π using
np.linspace, which creates 1000 evenly spaced values. This ensures a
smooth plot.
Next, we compute the corresponding rrr values using the given function
r=1+cos⁡(2θ)r=1+\cos(2\theta)r=1+cos(2θ). This is done using np.cos to
handle the cosine operation element-wise on the θ\theta θ array.
We then set up a figure with a size of 8x8 inches for better visibility. The
subplot is created with a polar projection using plt.subplot(111,
projection='polar'). This transforms the plot into a polar coordinate system.
The plot is drawn using ax.plot, with the θ\theta θ and rrr arrays as inputs.
We choose a purple color and set the line width to 2 for aesthetic appeal.
The title of the plot is set to 'Polar Plot of r = 1 + cos(2θ)' with a font size of
15 and a navy color to make it stand out. The grid is enabled with a gray
color, dashed lines, and a line width of 0.5 to add subtle visual structure
without overwhelming the plot.
Finally, plt.show() is called to display the plot. This ensures that the plot is
rendered and visible to the audience.
【Trivia】
‣ The function r=1+cos⁡(2θ)r=1+\cos(2\theta)r=1+cos(2θ) is known as a
"four-leaved rose" or "quadrifolium" in polar coordinates.
‣ Polar plots are particularly useful in fields like meteorology, astronomy,
and engineering to represent data that has a directional component.
‣ The aesthetic aspects of data visualization, such as color choice, line
width, and grid style, can significantly impact the viewer's perception and
engagement with the plot.
‣ Matplotlib, the library used in this exercise, is one of the most popular
plotting libraries in Python and offers extensive customization options for
creating visually appealing plots.
38. Simple Network Graph Visualization
Importance★★★☆☆
Difficulty★★★☆☆
A client requires a visual representation of a network to better understand
the connections between different nodes.
Your task is to create a simple network graph with 30 nodes and 35 edges.
The graph should be visually appealing and emphasize artistic presentation.
Use Python to generate the data and create the visualization.

【Data Generation Code Example】

import random
import networkx as nx
## Create a network graph with 30 nodes and 35 edges
G = nx.gnm_random_graph(30, 35)
## Print the generated edges
print(list(G.edges))
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import networkx as nx
import random
## Create a network graph with 30 nodes and 35 edges
G = nx.gnm_random_graph(30, 35)
## Define a layout for the nodes
pos = nx.spring_layout(G)
## Draw the nodes with a specific size and color
nx.draw_networkx_nodes(G, pos, node_size=500, node_color='skyblue',
alpha=0.7)
## Draw the edges with a specific style
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray',
style='dashed')
## Draw the labels for the nodes
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
## Add a title to the graph
plt.title("Artistic Network Graph Visualization")
## Remove the axis
plt.axis('off')
## Display the graph
plt.show()

To create a visually appealing network graph, we first generate a random


graph with 30 nodes and 35 edges using the networkx library.
The spring_layout function is used to position the nodes in a way that
minimizes edge crossings and makes the graph more visually appealing.
We then draw the nodes with a specific size and color to enhance the visual
impact.
Edges are drawn with a dashed style to add an artistic touch.
Node labels are added for better understanding of the graph structure.
Finally, we add a title to the graph and remove the axis to focus on the
visual elements.
The matplotlib library is used to display the graph.
【Trivia】
‣ Network graphs are commonly used in various fields such as social
network analysis, biology, and computer science to represent relationships
between entities.
‣ The spring_layout algorithm in networkx is based on the Fruchterman-
Reingold force-directed algorithm, which positions nodes using attractive
and repulsive forces.
‣ Visual aesthetics in network graphs can significantly impact how easily
the information is interpreted by viewers.
39. Scatter Plot Art with Python
Importance★★★★☆
Difficulty★★★☆☆
You are a data visualization artist working on a new project to create an
aesthetically pleasing scatter plot for an art exhibit. Your task is to generate
a scatter plot with 800 points where each point has a different color and
size. Use Python to achieve this and ensure the plot is visually appealing
with a focus on artistic presentation.To generate the input data for the
scatter plot, use the provided code snippet. This code will create the data
needed for your plot. Your final plot should display the points with varying
colors and sizes, ensuring that it is a beautiful piece of visual art.
【Data Generation Code Example】

import numpy as np

## Generate random data for the scatter plot

## 800 points with x and y coordinates, sizes, and colors

data = {

'x': np.random.rand(800),

'y': np.random.rand(800),

'sizes': np.random.rand(800) * 100,

'colors': np.random.rand(800)

}
【Diagram Answer】

【Code Answer】

import numpy as np ## Import numpy for data generation


import matplotlib.pyplot as plt ## Import matplotlib for plotting
## Generate random data for the scatter plot
## 800 points with x and y coordinates, sizes, and colors
data = { 'x': np.random.rand(800), 'y': np.random.rand(800), 'sizes':
np.random.rand(800) * 100, 'colors': np.random.rand(800) }
## Create the scatter plot
plt.figure(figsize=(10, 6)) ## Set the figure size for better visualization
scatter = plt.scatter(data['x'], data['y'], s=data['sizes'], c=data['colors'],
cmap='viridis', alpha=0.6) ## Create scatter plot with colors and sizes
plt.colorbar(scatter, label='Color Scale') ## Add a color bar for reference
plt.title('Artistic Scatter Plot') ## Add a title to the plot
plt.xlabel('X-axis') ## Label the x-axis
plt.ylabel('Y-axis') ## Label the y-axis
plt.show() ## Display the plot

▸ To create an artistic scatter plot using Python, we first need to generate


the data. We use numpy to create arrays of random values for the x and y
coordinates, sizes, and colors of the points. Specifically, we generate 800
random values for each attribute, ensuring a diverse distribution.The
plotting is done using matplotlib.pyplot. We set the figure size to make the
plot visually appealing. The plt.scatter function is used to create the scatter
plot, where:
‣ data['x'] and data['y'] are the coordinates of the points.
‣ s=data['sizes'] sets the sizes of the points.
‣ c=data['colors'] sets the colors of the points.
‣ cmap='viridis' specifies the colormap to use.
‣ alpha=0.6 makes the points semi-transparent for a better visual effect.We
add a color bar using plt.colorbar to provide a reference for the color scale.
Finally, we label the axes and add a title to complete the artistic
presentation.This exercise focuses on the artistic aspect of data
visualization, demonstrating how Python can be used not only for analytical
purposes but also for creating visually stunning art.
【Trivia】
The use of colormaps in data visualization is crucial for both scientific
accuracy and artistic appeal. Matplotlib offers a variety of colormaps, such
as 'viridis', 'plasma', 'inferno', and 'magma', which are perceptually uniform.
This means they are designed to be accurate and aesthetically pleasing to
the human eye, maintaining consistent brightness and color differentiation
across their range.
40. Pie Chart of Tree Distribution
Importance★★★★☆
Difficulty★★★☆☆
A forest management company wants to visualize the distribution of
different types of trees in a forest to better understand the forest
composition.
They need a pie chart that artistically represents this distribution.
Create a Python script that generates a pie chart using the following tree
types and their respective counts: Oak (40), Pine (35), Birch (20), Maple
(15).
The pie chart should be visually appealing, with each section clearly labeled
and distinct colors used for each type of tree.
Ensure the chart includes a title and a legend.

【Data Generation Code Example】

import matplotlib.pyplot as plt


tree_types = ['Oak', 'Pine', 'Birch', 'Maple']
counts = [40, 35, 20, 15]
plt.pie(counts, labels=tree_types, autopct='%1.1f%%', startangle=140)
plt.title('Tree Distribution in the Forest')
plt.legend(tree_types)
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


tree_types = ['Oak', 'Pine', 'Birch', 'Maple']
counts = [40, 35, 20, 15]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
plt.pie(counts, labels=tree_types, autopct='%1.1f%%', startangle=140,
colors=colors, wedgeprops={'edgecolor': 'black'})
plt.title('Tree Distribution in the Forest')
plt.legend(tree_types, loc="best")
plt.axis('equal')
plt.show()

To create a visually appealing pie chart in Python, we use the matplotlib


library, which is a powerful tool for creating static, animated, and
interactive visualizations.
First, we import the library using import matplotlib.pyplot as plt.
Next, we define the data: tree_types contains the names of the tree types,
and counts contains the number of each type of tree.
In the pie chart, we use the plt.pie function to plot the data.
The labels parameter assigns the names to each section, and
autopct='%1.1f%%' displays the percentage value inside each section.
The startangle=140 parameter rotates the start of the pie chart for better
visual balance.
We use the colors parameter to assign specific colors to each section,
ensuring the chart is aesthetically pleasing.
The wedgeprops={'edgecolor': 'black'} parameter adds a black border to
each section, enhancing the visual separation.
The plt.title function adds a title to the chart, and plt.legend creates a legend
for clarity.
Finally, plt.axis('equal') ensures the pie chart is drawn as a circle, and
plt.show() displays the chart.
This approach ensures the pie chart is not only informative but also visually
appealing, aligning with the goal of creating artistic visualizations.
【Trivia】
‣ The pie chart was invented by William Playfair in 1801.
‣ Pie charts are best used for displaying data with a small number of
categories.
‣ Overuse of pie charts can lead to misinterpretation of data, especially
when there are too many categories.
‣ Matplotlib, the library used here, is one of the most popular plotting
libraries in Python and is widely used in data science and engineering.
41. Event Duration Histogram
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst working for an event management company. Your
task is to create a histogram of the durations of 200 different events in order
to visualize the distribution of event durations.
Generate the event duration data within the code itself.
The histogram should be visually appealing and artistic, emphasizing the
beauty of data visualization in Python.
Ensure that the histogram is labeled appropriately and has a title that
reflects its content.
Use the provided code snippet to generate the data and then create the
histogram.

【Data Generation Code Example】

import numpy as np
event_durations = np.random.normal(loc=50, scale=10, size=200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
event_durations = np.random.normal(loc=50, scale=10, size=200)
plt.figure(figsize=(10, 6))
plt.hist(event_durations, bins=20, color='skyblue', edgecolor='black')
plt.title('Distribution of Event Durations', fontsize=16)
plt.xlabel('Duration (minutes)', fontsize=14)
plt.ylabel('Frequency', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create a visually appealing histogram of event durations, we start by


generating synthetic data. The data is created using NumPy's
random.normal function, which generates 200 event durations following a
normal distribution with a mean (loc) of 50 minutes and a standard
deviation (scale) of 10 minutes. This ensures that the data is realistic and
varied.
We then use Matplotlib to create the histogram. We set the figure size to
make the plot larger and more readable. The hist function is used to create
the histogram, with 20 bins to provide a detailed view of the distribution.
The color of the bars is set to 'skyblue' with black edges to enhance visual
appeal.
The title and axis labels are added with increased font sizes to make them
stand out. A grid is added with dashed lines and slight transparency to
improve readability without overwhelming the visual. This combination of
settings ensures that the histogram is not only informative but also
aesthetically pleasing, highlighting the artistic side of data visualization in
Python.
【Trivia】
‣ Histograms are a type of bar chart that represents the distribution of
numerical data. They are particularly useful for understanding the
frequency distribution of data points in a dataset.
‣ The choice of bin size can significantly affect the appearance and
interpretability of a histogram. Too few bins can oversimplify the data,
while too many bins can overcomplicate it.
‣ Matplotlib is one of the most widely used libraries for data visualization
in Python. It provides a wide range of plotting functions and customization
options, making it a powerful tool for both simple and complex
visualizations.
42. Box Plot of House Prices
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst working for a real estate company. Your task is to
visualize the distribution of house prices to help the sales team understand
the market better.
Create a box plot of the distribution of the prices of 50 different houses.
Generate the data within your code and ensure the visualization is
artistically appealing.
Focus on making the plot visually engaging using Python's visualization
libraries.

【Data Generation Code Example】

import numpy as np
import pandas as pd
np.random.seed(0)
prices = np.random.normal(300000, 50000, 50)
prices = np.round(prices, -3)
prices = pd.Series(prices)
【Diagram Answer】

【Code Answer】

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(0)
prices = np.random.normal(300000, 50000, 50)
prices = np.round(prices, -3)
prices = pd.Series(prices)
plt.figure(figsize=(10, 6))
sns.boxplot(x=prices, color='skyblue')
plt.title('Distribution of House Prices', fontsize=16)
plt.xlabel('Price ($)', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create an artistically appealing box plot, we use Python's matplotlib and


seaborn libraries.
First, we generate the data for house prices using numpy to create 50
random prices following a normal distribution with a mean of 300,000 and
a standard deviation of 50,000.
We round these prices to the nearest thousand for realism.
Next, we use seaborn to create the box plot, setting the figure size to ensure
the plot is large enough to be easily readable.
We choose a sky blue color for the box plot to make it visually appealing.
We add a title and label the x-axis to provide context to the viewer.
Finally, we add a grid with dashed lines and some transparency to enhance
the visual appeal without overwhelming the plot.
【Trivia】
‣ Box plots are also known as whisker plots and are used to display the
distribution of a dataset based on a five-number summary: minimum, first
quartile (Q1), median, third quartile (Q3), and maximum.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ The np.random.seed(0) function ensures that the random numbers
generated are reproducible, which is useful for debugging and sharing code.
‣ In a box plot, the box represents the interquartile range (IQR), which
contains the middle 50% of the data, while the whiskers extend to the
smallest and largest values within 1.5 times the IQR from the quartiles.
43. Generate a Heatmap of a 12x12 Matrix of
Random Values
Importance★★★☆☆
Difficulty★★☆☆☆
A client needs to visualize a 12x12 matrix of random values to analyze data
distribution. Create a heatmap using Python that not only displays the data
but also emphasizes artistic visual appeal. The heatmap should be colorful
and aesthetically pleasing, suitable for a presentation. Generate the random
data within the code.
【Data Generation Code Example】

import numpy as np
data = np.random.rand(12, 12)
【Diagram Answer】

【Code Answer】

import numpy as np # Importing numpy for data generation


import matplotlib.pyplot as plt # Importing matplotlib for plotting
import seaborn as sns # Importing seaborn for enhanced visualization
data = np.random.rand(12, 12) # Generating a 12x12 matrix of random
values
plt.figure(figsize=(10, 8)) # Setting the figure size
sns.heatmap(data, annot=True, fmt=".2f", cmap='coolwarm',
linewidths=.5, cbar_kws={'shrink': .8}) # Creating the heatmap with
artistic elements
plt.title('Heatmap of 12x12 Matrix of Random Values') # Adding a title
plt.show() # Displaying the plot

To create an aesthetically pleasing heatmap, we start by generating a 12x12


matrix of random values using NumPy. This matrix serves as our input data.
We then use Matplotlib and Seaborn libraries to create the heatmap.
Matplotlib is a powerful plotting library in Python, and Seaborn builds on
top of it to provide a high-level interface for drawing attractive statistical
graphics.
The plt.figure(figsize=(10, 8)) command sets the size of the figure to ensure
the heatmap is large enough for clear visibility.
▸ The sns.heatmap function is used to create the heatmap. Several
parameters are used to enhance the visual appeal:
‣ annot=True adds the numerical values on the heatmap cells.
‣ fmt=".2f" formats the numerical values to two decimal places.
‣ cmap='coolwarm' sets the color palette to 'coolwarm', which provides a
visually appealing gradient.
‣ linewidths=.5 adds thin lines between the cells for better separation.
‣ cbar_kws={'shrink': .8} shrinks the color bar to 80% of its default size for
better proportion.
Finally, plt.title('Heatmap of 12x12 Matrix of Random Values') adds a title
to the heatmap, and plt.show() displays the plot.
This approach ensures that the heatmap is not only functional but also
visually appealing, making it suitable for presentations and reports.
【Trivia】
‣ Seaborn's heatmap function is highly customizable, allowing for various
color palettes, annotations, and other stylistic elements to be adjusted easily.
‣ The 'coolwarm' color palette is often used in heatmaps because it provides
a clear distinction between high and low values, making the data easier to
interpret.
‣ Heatmaps are widely used in various fields such as genomics, finance,
and marketing to visualize complex data sets and identify patterns or
anomalies quickly.
44. 3D Surface Plot of z = x^2 + y^2
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst for an art gallery, and you have been tasked with
creating a visually appealing 3D surface plot to showcase a mathematical
function. The function you need to visualize is z = x^2 + y^2. Your goal is
to create a stunning visual representation of this function using Python.
Write a Python code that generates and displays a 3D surface plot of the
function z = x^2 + y^2. Ensure that the plot is artistically appealing and
includes appropriate labels and a color map to enhance its visual appeal.
To get started, you can use the following code to generate the input data:

【Data Generation Code Example】

import numpy as np
# Generate x and y data points
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z=x+y
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Generate x and y data points
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z=x+y
# Create a figure and a 3D axis
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
surf = ax.plot_surface(x, y, z, cmap='viridis')
# Add color bar for reference
fig.colorbar(surf)
# Set labels for axes
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
# Set title for the plot
ax.set_title('3D Surface Plot of z = x^2 + y^2')
# Display the plot
plt.show()

To create a 3D surface plot of the function z = x^2 + y^2, we start by


generating the input data using numpy.
We use np.linspace to create evenly spaced values for x and y, ranging from
-5 to 5. These values are then combined into a meshgrid using np.meshgrid,
which creates a grid of x and y values. The function z = x^2 + y^2 is then
applied to these grid values to generate the z data.
In the plotting section, we use matplotlib to create a figure and a 3D axis
using fig.add_subplot(111, projection='3d'). We then plot the surface using
ax.plot_surface, specifying the x, y, and z data along with a colormap
('viridis') to enhance the visual appeal.
A color bar is added to the plot using fig.colorbar(surf) to provide a
reference for the color mapping. We also set labels for the x, y, and z axes
using ax.set_xlabel, ax.set_ylabel, and ax.set_zlabel respectively. Finally,
we set a title for the plot using ax.set_title and display the plot using
plt.show().
This approach ensures that the plot is not only functional but also visually
appealing, making it suitable for artistic presentations.
【Trivia】
‣ The viridis colormap used in the plot is designed to be perceptually
uniform, meaning that it is visually appealing and interpretable even when
printed in grayscale.
‣ The mpl_toolkits.mplot3d module in matplotlib is specifically designed
for creating 3D plots, providing various functions to customize and enhance
3D visualizations.
‣ Using meshgrid is a common technique in numerical computing to create
a grid of points over a specified range, which is particularly useful for
evaluating functions over a 2D domain.
45. Polar Plot of r = sin(3θ)
Importance★★★☆☆
Difficulty★★★☆☆
As a data visualization specialist, you are tasked with creating a visually
appealing polar plot for a client presentation. The plot should display the
function r = sin(3θ). Your goal is to not only plot the function but also
ensure the plot is visually striking and artistic. Write the Python code that
generates this plot.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
# Generate data for the polar plot
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.sin(3 * theta)
【Diagram Answer】

【Code Answer】

import numpy as np ## Importing numpy for numerical operations


import matplotlib.pyplot as plt ## Importing matplotlib for plotting
theta = np.linspace(0, 2 * np.pi, 1000) ## Generating theta values from 0
to 2*pi
r = np.sin(3 * theta) ## Calculating r for the given function r =
sin(3*theta)
plt.figure(figsize=(8, 8)) ## Setting up the figure size
ax = plt.subplot(111, projection='polar') ## Creating a polar subplot
ax.plot(theta, r, color='purple', linewidth=2) ## Plotting the function with
artistic choices
ax.set_title('Polar Plot of r = sin(3θ)', va='bottom') ## Setting the title of
the plot
ax.grid(True) ## Enabling the grid for better visualization
plt.show() ## Displaying the plot

In this exercise, you are required to create a polar plot for the function
r=sin⁡(3θ)r = \sin(3\theta)r=sin(3θ) and ensure it is visually appealing.
▸ The process involves the following steps:Import Necessary Libraries:
▸ We import numpy for numerical operations and matplotlib.pyplot for
plotting.Generate Data:
▸ We use numpy.linspace to create an array of values for θ\thetaθ ranging
from 0 to 2π2\pi2π. This gives us a smooth range of values to plot the
function.Compute the Function:
▸ We compute the corresponding rrr values using the given function
r=sin⁡(3θ)r = \sin(3\theta)r=sin(3θ).Set Up the Plot:
▸ We create a figure and a polar subplot. The projection='polar' argument
specifies that the plot should be in polar coordinates.Plot the Function:
▸ We plot rrr against θ\thetaθ using the ax.plot method. Here, we add
artistic elements by choosing a purple color and setting the line width to
2.Customize the Plot:
▸ We set the title of the plot and enable the grid for better visualization. The
va='bottom' argument in ax.set_title ensures that the title is positioned
appropriately.Display the Plot:
Finally, we use plt.show() to display the plot.This exercise helps in
understanding how to create polar plots and emphasizes the importance of
aesthetics in data visualization.
【Trivia】
Polar plots are a type of plot where data is displayed in terms of angles and
radii. This kind of plot is particularly useful in fields like physics and
engineering, where periodic functions or phenomena with a circular
symmetry are analyzed.
46. Simple Network Graph Visualization
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data visualization specialist tasked with creating an aesthetically
pleasing network graph for a client. The client wants a simple network
graph with 35 nodes and 40 edges. The graph should be visually appealing
and artistic, emphasizing the beauty of network structures. Use Python to
generate and display the graph.
【Data Generation Code Example】

import networkx as nx
import random
G = nx.Graph()
nodes = range(35)
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(40)]
G.add_nodes_from(nodes)
G.add_edges_from(edges)
【Diagram Answer】

【Code Answer】

import networkx as nx
import matplotlib.pyplot as plt
import random
G = nx.Graph()
nodes = range(35)
edges = [(random.choice(nodes), random.choice(nodes)) for _ in
range(40)]
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G, seed=42)
plt.figure(figsize=(10, 10))
nx.draw_networkx_nodes(G, pos, node_size=500, node_color='skyblue',
alpha=0.7)
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray', alpha=0.7)
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
plt.title("Artistic Network Graph", fontsize=20)
plt.axis('off')
plt.show()

To create an aesthetically pleasing network graph, we first need to generate


the nodes and edges.
We use the networkx library to create a graph object.
The graph is populated with 35 nodes and 40 edges, which are randomly
generated.
Next, we use the spring_layout function to position the nodes in a visually
appealing manner.
This layout algorithm simulates a force-directed layout, giving a natural and
balanced appearance to the graph.
We then use matplotlib to draw the graph.
The nodes are drawn with a sky blue color and a slight transparency to
enhance the visual appeal.
Edges are drawn in gray with a slight transparency to create a subtle, artistic
effect.
Node labels are added for clarity, and the graph title is set to "Artistic
Network Graph".
Finally, the axis is turned off to focus on the graph itself.
This combination of techniques results in a visually appealing and artistic
network graph.
【Trivia】
‣ The spring_layout algorithm in NetworkX is based on the Fruchterman-
Reingold force-directed algorithm, which models the graph as a physical
system.
‣ Network graphs are widely used in various fields, including social
network analysis, biology, and computer science, to visualize relationships
and interactions.
‣ Aesthetic graph drawing is a field of study that focuses on creating
visually appealing representations of graphs, balancing readability and
artistic expression.
47. Scatter Plot Art with Python
Importance★★★☆☆
Difficulty★★★☆☆
A client has requested a visually appealing scatter plot to be used in a
presentation. The scatter plot should contain 900 points, each with different
colors and sizes. The goal is to create an artistic scatter plot that captures
the audience's attention. The data for the scatter plot should be generated
within the code.
Write a Python script that generates and displays this scatter plot. Ensure
that the plot is visually striking and artistic.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(900)
y = np.random.rand(900)
colors = np.random.rand(900)
sizes = 1000 * np.random.rand(900)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(900)
y = np.random.rand(900)
colors = np.random.rand(900)
sizes = 1000 * np.random.rand(900)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create an artistic scatter plot in Python, we use the matplotlib library,


which is a powerful tool for creating a variety of visualizations.
First, we import the necessary libraries: numpy for generating random data
and matplotlib.pyplot for plotting.
We set a random seed using np.random.seed(0) to ensure reproducibility of
the random numbers. This means that every time we run the code, we get
the same random numbers, which helps in debugging and consistency.
Next, we generate 900 random points for the x and y coordinates using
np.random.rand(900). This function generates random numbers between 0
and 1.
For the colors of the points, we again use np.random.rand(900) to generate
900 random values. These values will be mapped to a color map to create a
gradient of colors.
The sizes of the points are generated by multiplying random values by 1000
using 1000 * np.random.rand(900). This ensures that the points have a
variety of sizes, adding to the visual appeal.
The plt.scatter function is used to create the scatter plot. We pass the x and
y coordinates, the colors, and the sizes as arguments. The alpha parameter is
set to 0.5 to make the points semi-transparent, and the cmap parameter is set
to 'viridis' to use a specific color map.
The plt.colorbar function adds a color bar to the plot, which helps in
understanding the mapping of colors to values.
Finally, we add a title and labels to the axes using plt.title, plt.xlabel, and
plt.ylabel. The plt.show function displays the plot.
This code creates a visually striking scatter plot with 900 points, each
having different colors and sizes, making it suitable for artistic
presentations.
【Trivia】
‣ The matplotlib library was originally created by John D. Hunter in 2003
and has since become one of the most widely used plotting libraries in
Python.
‣ The viridis color map used in this example is a perceptually uniform color
map, meaning it is designed to be easy to interpret by the human eye, even
for those with color vision deficiencies.
‣ Scatter plots are often used in data analysis to visualize the relationship
between two variables, but they can also be used creatively for artistic
purposes, as demonstrated in this example.
48. Plotting a Pie Chart of Insect Distribution
Importance★★★★☆
Difficulty★★☆☆☆
A client who owns a botanical garden wants to visualize the distribution of
different types of insects in their garden.
Create a pie chart to represent the following data:
Butterflies: 35%
Bees: 25%
Beetles: 20%
Dragonflies: 10%
Other insects: 10%
Ensure that the chart is not only accurate but also visually appealing,
adhering to the theme of 'Artistic Visuals in Python'.
Use matplotlib to create this visualization.
Below is the code to generate the data.
You need to write the complete code to generate and display the pie chart.

【Data Generation Code Example】

insect_data={'Butterflies':35,'Bees':25,'Beetles':20,'Dragonflies':10,'Other
insects':10}
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
insect_data={'Butterflies':35,'Bees':25,'Beetles':20,'Dragonflies':10,'Other
insects':10}
labels=list(insect_data.keys())
sizes=list(insect_data.values())
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']
explode=(0.1,0,0,0,0)
plt.figure(figsize=(8,8))
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f
%%',shadow=True,startangle=140)
plt.axis('equal')
plt.title('Distribution of Different Types of Insects in the
Garden',fontsize=14)
plt.show()

To create an artistic and visually appealing pie chart in Python, we use the
matplotlib library, which is highly versatile and capable of creating detailed
visualizations.
We start by importing the necessary library, matplotlib.pyplot, and numpy
for any additional numerical operations.
The data for the insect distribution is represented as a dictionary, with insect
types as keys and their respective percentages as values.
Next, we extract the labels and sizes from the dictionary, which will be used
in the pie chart.
We define a set of colors to make the chart visually distinct and appealing.
The explode parameter is used to highlight the first slice (Butterflies) by
pulling it out slightly from the pie.
The plt.pie() function is then used to create the pie chart. Here, we pass the
sizes, explode values, labels, colors, and other stylistic parameters such as
autopct for displaying the percentage, shadow for adding a shadow effect,
and startangle to rotate the start of the pie chart for better orientation.
Finally, plt.axis('equal') ensures that the pie chart is drawn as a circle, and
plt.title() adds a title to the chart. The chart is displayed using plt.show().
This approach ensures that the chart is not only accurate but also adheres to
an artistic theme, making the visualization both informative and
aesthetically pleasing.
【Trivia】
Pie charts were popularized by Florence Nightingale, who used them to
present medical statistics in the 1850s.
The largest pie chart ever made was used to represent the usage share of
different web colabs, created by Russel Neiss in 2010.
Matplotlib, the library used in this exercise, was originally created by John
D. Hunter in 2003 as a MATLAB alternative for Python.
49. Visualizing Movie Lengths with a Histogram
Importance★★★★☆
Difficulty★★☆☆☆
You are a data analyst working for a movie production company. Your task
is to create a visually appealing histogram that displays the distribution of
the lengths of 200 different movies. This histogram will be used in a
presentation to showcase the variety in movie lengths and to help in
planning future productions.
Generate the movie length data within your code and ensure that the
histogram is not only informative but also aesthetically pleasing. Use
artistic elements such as color, labels, and titles to enhance the visual
impact of the histogram.
Use the following code to generate the movie length data:

【Data Generation Code Example】

import numpy as np
np.random.seed(42)
movie_lengths = np.random.normal(loc=120, scale=30, size=200)
movie_lengths = [max(60, min(length, 240)) for length in movie_lengths]
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
movie_lengths = np.random.normal(loc=120, scale=30, size=200)
movie_lengths = [max(60, min(length, 240)) for length in movie_lengths]
plt.figure(figsize=(10, 6))
plt.hist(movie_lengths, bins=20, color='skyblue', edgecolor='black')
plt.title('Distribution of Movie Lengths', fontsize=16, fontweight='bold')
plt.xlabel('Movie Length (minutes)', fontsize=14)
plt.ylabel('Number of Movies', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

In this exercise, you are tasked with creating a histogram that visually
represents the lengths of 200 movies. The primary goal is to create a
visually appealing chart that can be used in a professional presentation.
First, we generate the movie length data using a normal distribution with a
mean of 120 minutes and a standard deviation of 30 minutes. We then
ensure that all movie lengths are within a realistic range (60 to 240
minutes). This is done using a list comprehension that constrains the values.
Next, we use the matplotlib library to create the histogram. The plt.hist
function is used to plot the data, with 20 bins for better granularity. The
color of the bars is set to 'skyblue' with black edges to make the histogram
visually appealing.
The title and axis labels are added with specific font sizes and weights to
enhance readability and aesthetics. The grid is enabled with dashed lines
and slight transparency to make the plot more professional. Finally, the
plt.show function displays the histogram.
This exercise emphasizes the importance of data visualization in making
data insights more accessible and engaging, especially in a professional
setting. By focusing on artistic elements, you can create charts that are not
only informative but also visually striking.
【Trivia】
‣ The normal distribution, also known as the Gaussian distribution, is
commonly used in statistics and natural sciences to represent real-valued
random variables with a symmetrical distribution.
‣ Matplotlib is one of the most widely used plotting libraries in Python,
known for its versatility and ability to create a wide range of static,
animated, and interactive visualizations.
‣ A histogram is a graphical representation of the distribution of numerical
data, often used to show the frequency of data points within specified
ranges (bins). It is particularly useful for understanding the underlying
distribution of a dataset.
50. Mountain Heights Distribution Visualization
Importance★★★☆☆
Difficulty★★★☆☆
A mountain expedition company wants to analyze the height distribution of
mountains they operate on to improve their tour planning. They have
collected the heights (in meters) of 50 different mountains. Your task is to
visualize this data using a box plot to help them understand the distribution,
median, and possible outliers in mountain heights. Create the necessary data
within your code.
【Data Generation Code Example】

import numpy as np
## Generate sample data
heights = np.random.randint(1000, 8000, 50)
print(heights)
【Diagram Answer】

【Code Answer】

import numpy as np ## Import necessary libraries


import matplotlib.pyplot as plt ## Import matplotlib for plotting
## Generate sample data
heights = np.random.randint(1000, 8000, 50)
## Create a box plot for the distribution of mountain heights
plt.figure(figsize=(10, 6)) ## Set the figure size
plt.boxplot(heights) ## Create the box plot
plt.title('Distribution of Mountain Heights') ## Add a title to the plot
plt.xlabel('Mountains') ## Label x-axis
plt.ylabel('Height (meters)') ## Label y-axis
plt.show() ## Display the plot

The task requires creating a box plot to visualize the height distribution of
50 mountains.
First, the numpy library is used to generate an array of 50 random integers,
representing the heights of the mountains in meters.
This is done using np.random.randint(1000, 8000, 50), which generates
random heights between 1000 and 8000 meters.
Next, matplotlib.pyplot is used for plotting.
The plt.figure(figsize=(10, 6)) function sets the size of the plot to ensure it
is large enough to be visually appealing.
The plt.boxplot(heights) function creates the box plot based on the
generated mountain heights.
The plt.title, plt.xlabel, and plt.ylabel functions are used to add a title and
label the axes appropriately.
Finally, plt.show() displays the plot.
This box plot will help the mountain expedition company visualize the
distribution of mountain heights, showing the median, quartiles, and any
potential outliers, which is valuable for their planning and operational
decisions.
In this code, the emphasis is on creating a visually appealing and
informative plot.
The use of titles, axis labels, and figure size adjustments enhances the
readability and aesthetic appeal of the visualization.
The random generation of data within a realistic range ensures the plot is
representative of real-world scenarios.
【Trivia】
‣ The highest mountain in the world is Mount Everest, standing at 8,848
meters (29,029 feet).
‣ Box plots, also known as box-and-whisker plots, were first introduced by
John Tukey in 1970 as a part of Exploratory Data Analysis (EDA).
‣ A box plot displays the five-number summary of a dataset: minimum,
first quartile (Q1), median (Q2), third quartile (Q3), and maximum.
51. Heatmap Visualization of a 13x13 Matrix
Importance★★★☆☆
Difficulty★★☆☆☆
A client in the data visualization industry needs to create a heatmap to
represent a 13x13 matrix of random values for a presentation.
The heatmap should not only display the data but also be visually appealing
and artistic.
Your task is to generate this heatmap using Python, ensuring that the visual
aesthetics are given high priority.
Create the input data within the code and ensure that the final output is a
visually stunning heatmap.

【Data Generation Code Example】

import numpy as np
matrix = np.random.rand(13, 13)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
matrix = np.random.rand(13, 13)
plt.figure(figsize=(10, 8))
sns.heatmap(matrix, annot=False, cmap='viridis', cbar=True,
linewidths=0.5, linecolor='white')
plt.title('Artistic Heatmap of a 13x13 Matrix', fontsize=20)
plt.xlabel('X Axis', fontsize=15)
plt.ylabel('Y Axis', fontsize=15)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.show()

In this exercise, you will create a heatmap to visualize a 13x13 matrix of


random values.
The primary focus is on the artistic and aesthetic presentation of the
heatmap.
First, the numpy library is used to generate a 13x13 matrix of random
values.
Next, matplotlib and seaborn libraries are utilized to create and customize
the heatmap.
The seaborn.heatmap function is employed to generate the heatmap, with
the cmap parameter set to 'viridis' for a visually appealing color palette.
The linewidths and linecolor parameters add white grid lines for better
visual separation of cells.
Titles and axis labels are added with specific font sizes to enhance
readability and presentation.
Finally, the plt.show() function displays the heatmap.
This code ensures that the heatmap is not only functional but also
artistically pleasing, making it suitable for professional presentations.
【Trivia】
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ The 'viridis' colormap is often preferred for visualizations because it is
perceptually uniform, meaning it looks good and is easy to interpret for
viewers.
‣ Heatmaps are widely used in various fields, including bioinformatics, to
visualize data matrices such as gene expression data.
52. 3D Surface Plot of cos(x^2 + y^2)
Importance★★★☆☆
Difficulty★★★☆☆
You are a data visualization specialist working for a company that wants to
create an engaging and artistic 3D surface plot for their upcoming
presentation. The function to be visualized is
z=cos⁡(x+y)z=\cos(x^2+y^2)z=cos(x+y).
Your task is to write a Python code that generates this 3D surface plot. The
plot should be visually appealing and artistic, capturing the essence of the
function in a way that is both informative and aesthetically pleasing.
The plot should include:
‣ A title
‣ Axis labels
‣ A color map that enhances the visual appeal
Use the provided data generation code to create the input data for the plot.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)
z = np.cos(x + y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)
z = np.cos(x + y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create a 3D surface plot
surf = ax.plot_surface(x, y, z, cmap='viridis')
# Add a color bar which maps values to colors
fig.colorbar(surf)
# Set plot title and labels
ax.set_title('3D Surface Plot of cos(x^2 + y^2)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

This exercise focuses on creating a visually appealing 3D surface plot using


Python. The function z=cos⁡(x+y)z=\cos(x^2+y^2)z=cos(x+y) is chosen for
its interesting and intricate pattern, which makes it ideal for artistic
visualizations.
First, we generate the data points for the plot using numpy. The linspace
function creates evenly spaced values for xxx and yyy within the range of
-5 to 5. The meshgrid function then creates a grid of xxx and yyy values,
which are used to compute the corresponding zzz values based on the given
function.
In the plotting section, we use matplotlib to create the 3D surface plot. The
plot_surface function is used to generate the surface plot, and the viridis
colormap is chosen for its aesthetic appeal. A color bar is added to provide
a reference for the color mapping.
Finally, we set the title and labels for the axes to make the plot informative.
This combination of data generation and artistic visualization techniques
results in a plot that is both engaging and informative, suitable for
presentations and other visual displays.
【Trivia】
‣ The viridis colormap is often preferred for scientific visualizations
because it is perceptually uniform, meaning it is easier to interpret the data
accurately across its range.
‣ The mpl_toolkits.mplot3d module in matplotlib provides tools for
creating 3D plots, making it a powerful library for data visualization in
Python.
‣ 3D surface plots are commonly used in fields such as geography,
meteorology, and engineering to visualize complex surfaces and data
distributions.
53. Polar Plot Art with Python
Importance★★★☆☆
Difficulty★★★☆☆
A client needs to create an artistic visualization for a presentation. They
want to show a polar plot of the function r=1−sin⁡(θ)r=1-
\sin(\theta)r=1−sin(θ). Your task is to write a Python script that generates
this plot in a visually appealing manner. The focus should be on creating an
aesthetically pleasing and artistic representation of the plot. Ensure that the
plot is colorful and has artistic elements such as customized markers, line
styles, and background color.
【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 - np.sin(theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000) # Generate theta values
r = 1 - np.sin(theta) # Compute r values
plt.figure(facecolor='black') # Set background color to black
ax = plt.subplot(111, projection='polar') # Create polar plot
ax.plot(theta, r, color='cyan', linewidth=2, linestyle='--', marker='o',
markersize=4, markerfacecolor='magenta') # Plot with artistic elements
ax.set_facecolor('black') # Set plot background color to black
ax.grid(color='white', linestyle=':') # Customize grid lines
plt.title('Artistic Polar Plot of r = 1 - sin(θ)', color='white') # Set title with
white color
plt.show() # Display the plot

To create a visually appealing polar plot of the function r=1−sin⁡(θ)r=1-


\sin(\theta)r=1−sin(θ), we start by importing the necessary libraries: NumPy
for numerical operations and Matplotlib for plotting.
We generate 1000 evenly spaced values of θ\theta θ ranging from 0 to
2π2\pi 2π using np.linspace.
We then compute the corresponding rrr values using the given function.
The plot is created with a black background for a dramatic effect.
We use plt.subplot(111, projection='polar') to specify that the plot should be
in polar coordinates.
The plot line is customized with cyan color, dashed line style, and magenta
markers to enhance its artistic appeal.
We set the plot's background color to black and customize the grid lines to
be white and dotted for better visibility.
Finally, we add a title in white to contrast with the black background and
display the plot using plt.show().
This approach ensures that the plot is not just informative but also visually
captivating, making it suitable for artistic presentations.
【Trivia】
‣ The polar coordinate system is a two-dimensional coordinate system
where each point is determined by a distance from a reference point and an
angle from a reference direction.
‣ The function r=1−sin⁡(θ)r=1-\sin(\theta)r=1−sin(θ) creates a cardioid
shape, which is a heart-like curve that is often used in mathematical art.
‣ Matplotlib allows extensive customization of plots, including colors, line
styles, markers, and backgrounds, making it a powerful tool for creating
artistic visualizations.
‣ The use of black backgrounds in plots can help highlight the data and
make colors appear more vibrant and striking.
54. Simple Network Graph with Artistic
Visualization
Importance★★★☆☆
Difficulty★★★★☆
You are tasked with creating a visually appealing network graph for a client
who is a modern art enthusiast. The client wants a network graph with 40
nodes and 45 edges, but the emphasis is on the artistic and aesthetic quality
of the visualization.
Your task is to generate the data for the nodes and edges and then create a
Python script that will produce a graph that is not only functional but also
visually striking.
Ensure that the graph is colorful, well-labeled, and artistically pleasing.
Use Python libraries to achieve this and include detailed comments in your
code to explain your artistic choices.

【Data Generation Code Example】

import networkx as nx
import random
G = nx.gnm_random_graph(40, 45)
【Diagram Answer】

【Code Answer】

import networkx as nx
import matplotlib.pyplot as plt
import random
G = nx.gnm_random_graph(40, 45)
pos = nx.spring_layout(G, seed=42) # For consistent layout
plt.figure(figsize=(12, 12))
colors = [plt.cm.viridis(random.random()) for node in G.nodes()]
nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=500,
alpha=0.8)
edges = nx.draw_networkx_edges(G, pos, arrowstyle='-|>', arrowsize=10,
edge_color='black', width=2)
labels = nx.draw_networkx_labels(G, pos, font_size=12,
font_color='white')
plt.title("Artistic Network Graph", fontsize=20)
plt.axis('off')
plt.show()

To create a visually appealing network graph, we first generate a random


graph with 40 nodes and 45 edges using the networkx library.
The spring_layout function is used to position the nodes in a way that is
visually balanced and aesthetically pleasing. This layout algorithm
simulates a force-directed graph drawing, which is often used to create
visually appealing graphs.
We set a seed for the layout to ensure consistency in the node positions each
time the code is run.
The matplotlib library is used for the actual drawing of the graph. We create
a figure with a specified size to ensure the graph is large enough to be
visually impactful.
Node colors are randomly assigned using the viridis colormap, which
provides a range of visually distinct colors. This adds to the artistic quality
of the graph.
The edges are drawn with an arrow style to give a sense of direction and
flow, and they are colored black to contrast with the colorful nodes.
Labels are added to the nodes to provide additional information and to
enhance the visual appeal. The font size and color are chosen to ensure
readability.
Finally, we add a title to the graph and remove the axis to focus attention on
the network itself. The combination of these elements creates a graph that is
both functional and artistically pleasing.
【Trivia】
‣ The spring_layout algorithm used in this example is based on the
Fruchterman-Reingold algorithm, which simulates a physical system to
position the nodes in a visually appealing way.
‣ The viridis colormap is designed to be perceptually uniform, meaning that
it is visually appealing and interpretable even for individuals with color
vision deficiencies.
‣ Network graphs are often used in various fields such as social network
analysis, biology, and computer science to visualize relationships and
interactions between entities.
‣ The choice of colors, layout, and other visual elements can significantly
impact the readability and interpretability of a network graph, making it an
important aspect of data visualization.
55. Scatter Plot Art with Python
Importance★★★☆☆
Difficulty★★★☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to showcase in their upcoming digital art exhibition.
They need a scatter plot with 1000 points, each having different colors and
sizes to create a vibrant and artistic visual.
Your task is to generate this scatter plot using Python.
Ensure that the scatter plot is visually engaging and aesthetically pleasing.
Use the provided code to generate the input data.
Focus on the artistic aspect of the plot while maintaining the code's
functionality.
Here is the code to generate the input data:

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
x = np.random.rand(1000)
y = np.random.rand(1000)
colors = np.random.rand(1000)
area = (30 * np.random.rand(1000))**2 # 0 to 15 point radii
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(1000)
y = np.random.rand(1000)
colors = np.random.rand(1000)
area = (30 * np.random.rand(1000))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

In this exercise, you will create an artistic scatter plot using Python's
Matplotlib library.
The scatter plot will contain 1000 points, each with varying colors and sizes
to enhance its visual appeal.
The provided code generates the input data for the scatter plot.
The numpy library is used to create random data for the x and y
coordinates, colors, and sizes of the points.
The np.random.seed(0) ensures that the random data is reproducible.
The x and y coordinates are generated using np.random.rand(1000), which
creates 1000 random values between 0 and 1.
The colors are also generated using np.random.rand(1000), providing a
unique color for each point.
The sizes of the points are determined by area = (30 *
np.random.rand(1000))**2, which creates random sizes up to 15 point radii.
The plt.scatter function is used to create the scatter plot, where s=area sets
the sizes of the points, c=colors sets the colors, and alpha=0.5 makes the
points semi-transparent.
Finally, plt.title, plt.xlabel, and plt.ylabel add the title and axis labels to the
plot.
The plt.show() function displays the scatter plot.
This exercise emphasizes the artistic aspect of data visualization,
encouraging you to create visually engaging plots.
【Trivia】
‣ The Matplotlib library is one of the most widely used plotting libraries in
Python, known for its flexibility and extensive customization options.
‣ Scatter plots are useful for visualizing the relationship between two
variables and can be enhanced with colors and sizes to represent additional
dimensions of data.
‣ The concept of using data visualization as an art form is gaining
popularity, with many artists and data scientists exploring the intersection of
data and art.
‣ Random number generation in programming often uses a "seed" to ensure
reproducibility, allowing the same set of random numbers to be generated
each time the code is run.
56. Fish Distribution Pie Chart
Importance★★★☆☆
Difficulty★★☆☆☆
A local fish pond management company wants to visualize the distribution
of different types of fish in their pond to better understand the biodiversity.
They have the following fish types and their respective counts:
Carp: 45
Catfish: 30
Bass: 25
Trout: 20
Salmon: 10
Create a Python script to generate a pie chart that visually represents the
distribution of these fish types.
The chart should be artistically appealing and include labels for each fish
type.

【Data Generation Code Example】

# Data creation for fish distribution

fish_types = ['Carp', 'Catfish', 'Bass', 'Trout', 'Salmon']

fish_counts = [45, 30, 25, 20, 10]


【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
# Data
fish_types = ['Carp', 'Catfish', 'Bass', 'Trout', 'Salmon']
fish_counts = [45, 30, 25, 20, 10]
# Colors
colors = plt.cm.viridis(np.linspace(0, 1, len(fish_types)))
# Pie chart
plt.figure(figsize=(8, 8))
plt.pie(fish_counts, labels=fish_types, colors=colors, autopct='%1.1f%%',
startangle=140,
wedgeprops={'edgecolor': 'black', 'linewidth': 1.5, 'antialiased':
True})
# Artistic enhancements
plt.title('Fish Distribution in the Pond', fontsize=16, fontweight='bold')
plt.gca().set_aspect('equal') # Equal aspect ratio ensures that pie is drawn
as a circle.
plt.show()

This exercise focuses on creating a visually appealing pie chart using


Python's Matplotlib library.
First, we import the necessary libraries: matplotlib.pyplot for plotting and
numpy for numerical operations.
We then define the data for the fish types and their respective counts.
To enhance the visual appeal, we use the viridis colormap from Matplotlib
to assign distinct colors to each fish type.
The plt.pie function is used to create the pie chart, with parameters for
labels, colors, percentage display (autopct), and starting angle (startangle).
The wedgeprops parameter is used to add a black edge around each slice,
making the chart more visually distinct.
We also set the title with increased font size and bold weight for emphasis.
Finally, plt.gca().set_aspect('equal') ensures that the pie chart is drawn as a
perfect circle.
The plt.show() function displays the chart.
【Trivia】
‣ The viridis colormap is often preferred for its perceptual uniformity,
meaning it is visually appealing and interpretable by people with color
vision deficiencies.
‣ Pie charts are best used for displaying parts of a whole, especially when
there are fewer categories. For many categories, other chart types like bar
charts may be more effective.
‣ The autopct parameter in plt.pie can take a format string or a function to
format the percentage labels.
57. Fruit Weight Histogram
Importance★★★☆☆
Difficulty★★★☆☆
A fruit market wants to analyze the distribution of weights of different fruits
to optimize their packaging process.
They have collected the weights of 200 different fruits and need a visual
representation of this data.
Your task is to create a histogram of the weights of these fruits using
Python.
The histogram should be visually appealing and artistic.
Generate the weights data within the code itself.
Ensure the histogram is not only functional but also aesthetically pleasing.
Use colors, labels, and other visual elements to enhance its artistic value.

【Data Generation Code Example】

import numpy as np
weights = np.random.normal(loc=150, scale=30, size=200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
weights = np.random.normal(loc=150, scale=30, size=200)
plt.figure(figsize=(10, 6))
sns.histplot(weights, bins=20, kde=True, color='skyblue',
edgecolor='black')
plt.title('Distribution of Fruit Weights', fontsize=20, fontweight='bold')
plt.xlabel('Weight (grams)', fontsize=15)
plt.ylabel('Frequency', fontsize=15)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create an artistic and visually appealing histogram of fruit weights, we


start by generating synthetic data.
We use NumPy to create an array of 200 weights, assuming a normal
distribution with a mean of 150 grams and a standard deviation of 30
grams.
This simulates real-world data where fruit weights vary around a central
value.
For the visualization, we use Matplotlib and Seaborn, two powerful
libraries for creating plots in Python.
Matplotlib provides the basic plotting functionality, while Seaborn adds
advanced statistical plotting capabilities and enhances the aesthetics of the
plots.
We begin by setting the figure size to make the plot large enough for
detailed visualization.
We then use Seaborn's histplot function to create the histogram.
The bins parameter is set to 20 to divide the data into 20 intervals.
The kde=True parameter adds a Kernel Density Estimate line, which
smooths the distribution curve, providing a better visual understanding of
the data distribution.
To enhance the visual appeal, we set the color of the bars to 'skyblue' and
the edge color to 'black'.
We add a title and axis labels with increased font sizes and bold text for
better readability.
Finally, we enable the grid with a dashed line style and some transparency
to make the plot more visually engaging.
This approach not only ensures the histogram is informative but also makes
it aesthetically pleasing, aligning with the goal of creating visual art with
Python.
【Trivia】
‣ Seaborn is built on top of Matplotlib and integrates closely with Pandas
data structures, making it easier to work with DataFrames.
‣ The Kernel Density Estimate (KDE) is a non-parametric way to estimate
the probability density function of a random variable, providing a smooth
curve that represents the data distribution.
‣ Matplotlib's customization options allow for extensive control over plot
appearance, including colors, fonts, and grid styles, making it a versatile
tool for creating both simple and complex visualizations.
‣ Using a normal distribution to generate synthetic data is common in data
visualization exercises because many real-world phenomena follow a
normal distribution.
58. Box Plot of Tree Ages
Importance★★★☆☆
Difficulty★★☆☆☆
You are working as a data analyst for a forestry company.
The company has collected data on the ages of 50 different trees in a forest.
Your task is to create a visually appealing box plot to represent the
distribution of these ages.
Use Python to generate the data and create the plot.
The goal is to focus on the artistic and visual aspects of the plot to make it
engaging and informative.

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
ages = np.random.randint(5, 100, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
ages = np.random.randint(5, 100, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(ages, patch_artist=True, boxprops=dict(facecolor='lightblue',
color='blue'), whiskerprops=dict(color='blue'),
capprops=dict(color='blue'), medianprops=dict(color='red'))
plt.title('Distribution of Tree Ages')
plt.xlabel('Trees')
plt.ylabel('Age')
plt.grid(True)
plt.show()

To create a visually appealing box plot of the ages of 50 different trees, we


begin by importing the necessary libraries: numpy for generating random
data and matplotlib.pyplot for plotting.
We use numpy to generate an array of 50 random integers between 5 and
100, representing the ages of the trees.
The np.random.seed(0) function ensures that the random data is
reproducible.
Next, we use matplotlib.pyplot to create the box plot.
We set the figure size to 10x6 inches for better visibility.
The plt.boxplot function is used to create the box plot, with several
parameters to enhance its visual appeal.
The patch_artist=True parameter allows us to fill the box with color.
We set boxprops, whiskerprops, capprops, and medianprops to customize
the colors of the box, whiskers, caps, and median line, respectively.
The box is filled with light blue, the whiskers and caps are blue, and the
median line is red.
We add a title, x-axis label, and y-axis label to the plot for better
understanding.
Finally, we enable the grid for better readability and display the plot using
plt.show().
This approach ensures that the box plot is not only informative but also
visually engaging.
【Trivia】
‣ Box plots, also known as whisker plots, were introduced by John Tukey
in 1977.
‣ They are useful for displaying the distribution of data and identifying
outliers.
‣ The box represents the interquartile range (IQR), which contains the
middle 50% of the data.
‣ The line inside the box represents the median, while the whiskers extend
to the smallest and largest values within 1.5 times the IQR from the lower
and upper quartiles, respectively.
‣ Points outside this range are considered outliers and are plotted
individually.
59. Generate a 14x14 Heatmap with Artistic Flair
Importance★★★☆☆
Difficulty★★★☆☆
You are tasked with creating a visually appealing heatmap of a 14x14
matrix filled with random values. The goal is to produce an artistic
representation of the data, focusing on aesthetics and visual impact.
Use Python to generate the matrix and create the heatmap. Your heatmap
should not only display the data but also be visually engaging and artistic.
Ensure that the code you write generates the data within the script itself.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(14, 14)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(14, 14)
plt.figure(figsize=(10, 8))
sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis", linewidths=.5,
linecolor='white')
plt.title("Artistic 14x14 Heatmap", fontsize=20)
plt.xlabel("X-axis", fontsize=15)
plt.ylabel("Y-axis", fontsize=15)
plt.show()

To create an artistic heatmap in Python, we first generate a 14x14 matrix


filled with random values using NumPy.
This matrix serves as our input data.
The matplotlib and seaborn libraries are then used to create and customize
the heatmap.
Seaborn's heatmap function is particularly useful for creating visually
appealing heatmaps with various customization options.
We set the figure size to ensure the heatmap is large and clear.
The annot parameter is set to True to display the data values within each
cell, and fmt is set to ".2f" to format these values to two decimal places.
The cmap parameter is set to "viridis" to apply a visually pleasing color
map.
We add grid lines between cells using linewidths and linecolor.
Finally, we set the title and axis labels to enhance the overall appearance of
the heatmap.
【Trivia】
‣ The viridis colormap is often preferred for its perceptual uniformity,
making it easier to interpret data accurately.
‣ Seaborn is built on top of matplotlib and provides a high-level interface
for drawing attractive statistical graphics.
‣ Heatmaps are widely used in various fields, including bioinformatics, to
visualize gene expression data and other complex datasets.
60. 3D Surface Plot of a Mathematical Function
Importance★★★★☆
Difficulty★★★☆☆
You are working for a company that specializes in creating visually
appealing data visualizations for various clients. One of your clients is
interested in a 3D surface plot of the function z=exp⁡(−x)⋅sin⁡(y)z=\exp(-
x^2)\cdot \sin(y)z=exp(−x)⋅sin(y). Your task is to create a Python script that
generates this plot. The goal is not only to produce the plot but also to
ensure that the visualization is artistically appealing and visually engaging.
Use the provided code to generate the input data.
【Data Generation Code Example】

import numpy as np
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
x, y = np.meshgrid(x, y)
z = np.exp(-x**2) * np.sin(y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-2, 2, 100) # Generate 100 points between -2 and 2 for x
y = np.linspace(-2, 2, 100) # Generate 100 points between -2 and 2 for y
x, y = np.meshgrid(x, y) # Create a meshgrid for x and y
z = np.exp(-x**2) * np.sin(y) # Calculate z based on the given function
fig = plt.figure() # Create a new figure
ax = fig.add_subplot(111, projection='3d') # Add a 3D subplot
ax.plot_surface(x, y, z, cmap='viridis') # Plot the surface with 'viridis'
colormap
ax.set_title('3D Surface Plot of $z = \exp(-x^2) \cdot \sin(y)$') # Set the
title
ax.set_xlabel('X axis') # Label the X axis
ax.set_ylabel('Y axis') # Label the Y axis
ax.set_zlabel('Z axis') # Label the Z axis
plt.show() # Display the plot

To create a visually appealing 3D surface plot using Python, we use the


matplotlib library, which is a comprehensive library for creating static,
animated, and interactive visualizations in Python.
First, we generate the input data for the plot. We use numpy to create a
range of values for xxx and yyy between -2 and 2, with 100 points each.
The meshgrid function is used to create a grid of xxx and yyy values, which
is essential for creating 3D plots. The function z=exp⁡(−x)⋅sin⁡(y)z=\exp(-
x^2)\cdot \sin(y)z=exp(−x)⋅sin(y) is then computed using these xxx and yyy
values.
Next, we create a figure and a 3D subplot using matplotlib. The
plot_surface method is used to plot the surface, and we apply the 'viridis'
colormap to make the plot visually appealing. Colormaps are essential in
data visualization as they help in distinguishing different ranges of values
clearly. The title and axis labels are added to provide context to the plot.
Finally, the plt.show() function is called to display the plot.
This exercise not only demonstrates how to create a 3D surface plot but also
emphasizes the importance of aesthetics in data visualization. By choosing
appropriate colormaps and labels, we can make our plots more informative
and engaging.
【Trivia】
‣ The viridis colormap is often preferred in data visualization because it is
perceptually uniform, meaning that the perceived change in color is
consistent across the range of data values.
‣ 3D surface plots are particularly useful in visualizing mathematical
functions and data that depend on two independent variables. They can
provide insights that are not easily discernible in 2D plots.
‣ The matplotlib library, used in this exercise, is one of the most widely
used plotting libraries in Python. It is highly customizable and supports a
wide range of plot types.
61. Polar Plot of Cosine Function
Importance★★★★☆
Difficulty★★★☆☆
A customer wants to visualize the polar plot of the function r=cos⁡(4θ)r =
\cos(4\theta)r=cos(4θ). Your task is to write a Python script that generates
this plot. This exercise aims to emphasize the artistic aspect of Python
visualizations. Please ensure the plot is visually appealing and follows good
aesthetic practices. The input data should be generated within the script.
【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.cos(4 * theta)
【Diagram Answer】

【Code Answer】

import numpy as np ##Import necessary libraries


import matplotlib.pyplot as plt ##Import necessary libraries
theta = np.linspace(0, 2 * np.pi, 1000) ##Generate theta values
r = np.cos(4 * theta) ##Compute r based on the given function
plt.figure(figsize=(8, 8)) ##Create a figure with specific size
ax = plt.subplot(111, projection='polar') ##Create a polar subplot
ax.plot(theta, r, color='blue', linewidth=2) ##Plot the function with
specific color and linewidth
ax.set_title("Polar Plot of r = cos(4θ)", va='bottom') ##Set the title of the
plot
plt.show() ##Display the plot

To create a polar plot of the function r=cos⁡(4θ)r = \cos(4\theta)r=cos(4θ),


we start by importing the necessary libraries: numpy for numerical
operations and matplotlib.pyplot for plotting.
First, we generate an array of theta values ranging from 0 to 2π2\pi2π using
np.linspace. This function creates 1000 evenly spaced values, which
ensures a smooth plot.
Next, we compute the corresponding r values using the formula r=cos⁡(4θ)r
= \cos(4\theta)r=cos(4θ). This gives us the radial coordinates for our plot.
We then create a figure with a specified size using plt.figure(figsize=(8, 8)).
The figsize parameter ensures that our plot is large enough to be visually
appealing.
To create a polar plot, we use plt.subplot(111, projection='polar'), which
sets up a subplot with a polar projection.
We plot the theta and r values using ax.plot(theta, r, color='blue',
linewidth=2). Here, we specify the color and line width to enhance the
visual appearance of the plot.
Finally, we set the title of the plot using ax.set_title("Polar Plot of r =
cos(4θ)", va='bottom') and display the plot with plt.show(). The va
parameter aligns the title vertically.
This code results in a visually appealing polar plot of the given function,
emphasizing the artistic aspect of Python visualizations.
【Trivia】
‣ Polar plots are used to represent data in a circular format, where each
point is determined by an angle and a radius.
‣ The function r=cos⁡(4θ)r = \cos(4\theta)r=cos(4θ) creates a four-petaled
rose plot, also known as a rhodonea curve.
‣ Polar plots are commonly used in fields like meteorology, aviation, and
navigation to represent directional data.
‣ In Python, the matplotlib library provides extensive capabilities for
creating and customizing polar plots, making it a powerful tool for data
visualization.
‣ The aesthetics of a plot, including color, line width, and layout,
significantly impact its readability and visual appeal, highlighting the
importance of good design practices in data visualization.
62. Scatter Plot with Artistic Flair
Importance★★★☆☆
Difficulty★★★★☆
A company wants to create a unique and visually appealing scatter plot for
their annual report. They have asked you to generate a scatter plot with
1100 points, where each point has different colors and sizes to make the
chart more engaging.Use Python to create the plot, ensuring that the final
visual output is aesthetically pleasing and demonstrates a high level of
artistry in data visualization.Write a Python code that:Generates 1100 data
points with random x and y coordinates.Assigns a random color and size to
each point.Plots these points on a scatter plot.Your goal is to focus on the
artistic aspects of the plot. Use transparency, color gradients, and varying
sizes to enhance the visual appeal.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
# # Generate random data
np.random.seed(42) # # For reproducibility
x = np.random.rand(1100) # # Random x coordinates
y = np.random.rand(1100) # # Random y coordinates
colors = np.random.rand(1100) # # Random colors
sizes = 1000 * np.random.rand(1100) # # Random sizes
【Diagram Answer】

【Code Answer】

import numpy as np # # Import numpy for numerical operations


import matplotlib.pyplot as plt # # Import matplotlib for plotting
# # Generate random data
np.random.seed(42) # # For reproducibility
x = np.random.rand(1100) # # Random x coordinates
y = np.random.rand(1100) # # Random y coordinates
colors = np.random.rand(1100) # # Random colors
sizes = 1000 * np.random.rand(1100) # # Random sizes
# # Create a scatter plot
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis') # # Use
viridis colormap for aesthetics
plt.colorbar() # # Add color bar to show color scale
plt.title('Artistic Scatter Plot') # # Add title
plt.xlabel('X Axis') # # Label X axis
plt.ylabel('Y Axis') # # Label Y axis
plt.show() # # Display the plot

This exercise focuses on creating an artistically pleasing scatter plot using


Python's matplotlib library. First, we generate 1100 random data points for
the x and y coordinates, ensuring reproducibility by setting a random
seed.Next, each point is assigned a random color and size to enhance the
visual appeal. The 'viridis' colormap is used for its aesthetically pleasing
gradient. Transparency is added by setting alpha to 0.5, making overlapping
points more visually interesting.The scatter plot is then created using the
scatter function, with the colorbar function adding a color scale for
reference. Titles and axis labels are included to complete the
visualization.This artistic approach to data visualization helps in creating
engaging and visually appealing plots, which can be particularly useful in
presentations and reports.
【Trivia】
‣ The viridis colormap is often used for its perceptually uniform properties,
meaning it looks consistent to viewers with different forms of color
blindness.
‣ Transparency in plots (alpha parameter) can help visualize data density by
showing overlapping points more clearly.
‣ Aesthetic visualizations not only make data more engaging but also can
help in better understanding and interpreting complex data sets.
63. Histogram Visualization of Song Lengths
Importance★★★★☆
Difficulty★★★☆☆
You are working as a data analyst for a music streaming service. Your task
is to create a visually appealing histogram to show the distribution of song
lengths in the service's library. To do this, you will generate a dataset of 200
different song lengths (in seconds) and create a histogram to visualize this
data.Generate the dataset within your code, then write the code to create the
histogram. The focus should be on making the histogram not only
informative but also artistically appealing.
【Data Generation Code Example】

import numpy as np
# Generate random song lengths between 120 and 600 seconds (2 to 10
minutes)
np.random.seed(0) # For reproducibility
song_lengths = np.random.randint(120, 600, 200)
【Diagram Answer】

【Code Answer】

import numpy as np # Importing numpy for numerical operations


import matplotlib.pyplot as plt # Importing matplotlib for plotting
# Generate random song lengths between 120 and 600 seconds (2 to 10
minutes)
np.random.seed(0) # For reproducibility
song_lengths = np.random.randint(120, 600, 200)
# Create histogram
plt.figure(figsize=(10, 6)) # Setting the figure size
plt.hist(song_lengths, bins=20, color='skyblue', edgecolor='black') #
Creating the histogram with custom colors and edge color
plt.title('Distribution of Song Lengths', fontsize=15) # Adding title with
larger font size
plt.xlabel('Length (seconds)', fontsize=12) # Adding x-axis label with
larger font size
plt.ylabel('Number of Songs', fontsize=12) # Adding y-axis label with
larger font size
plt.grid(True, linestyle='--', alpha=0.7) # Adding a grid with dashed lines
and some transparency
plt.xticks(fontsize=10) # Customizing x-axis tick labels
plt.yticks(fontsize=10) # Customizing y-axis tick labels
plt.show() # Displaying the plot

The objective of this exercise is to create an aesthetically pleasing


histogram that visualizes the distribution of song lengths in a music library.
First, the code imports necessary libraries: numpy for generating random
data and matplotlib.pyplot for creating the plot.
A seed is set using np.random.seed(0) to ensure the random data is
reproducible. The dataset of song lengths is generated using
np.random.randint(120, 600, 200), which creates 200 random integers
between 120 and 600 seconds.
The code then proceeds to create a histogram using plt.hist(). The bins
parameter is set to 20, which defines the number of bins in the histogram.
The color of the bars is set to 'skyblue' and the edges of the bars are colored
black for better visual distinction.
▸ Several aesthetic enhancements are made to the plot:
‣ The figure size is adjusted to 10x6 inches for better visibility.
‣ The title and axis labels are added with increased font sizes for clarity.
‣ A grid is added with dashed lines (linestyle='--') and slight transparency
(alpha=0.7) to make the plot easier to read without being too distracting.
‣ The tick labels on both axes are customized for consistency and
readability.
Finally, plt.show() is called to display the plot. The resulting histogram not
only conveys the distribution of song lengths but also does so in a visually
appealing manner, making the data more engaging and easier to interpret.
【Trivia】
Histograms are a type of bar chart that represent the distribution of
numerical data. Each bar in a histogram represents the frequency (or count)
of data points that fall within a specific range of values, known as bins. By
adjusting the number of bins, you can control the granularity of the
distribution representation. Histograms are particularly useful in identifying
patterns, such as the central tendency, spread, and skewness of the data. In
the context of music streaming services, histograms can help in
understanding user preferences and optimizing playlist lengths to match
common listening habits.
64. Box Plot of Rock Weights
Importance★★★★☆
Difficulty★★☆☆☆
A geological research company needs to analyze the distribution of the
weights of 50 different rocks they have collected. They require a visually
appealing box plot to present their findings in a report.
Your task is to create a Python script that generates a box plot of the rock
weights.
The weights should be randomly generated for this exercise.
Ensure the plot is artistically appealing and informative.

【Data Generation Code Example】

import numpy as np
weights = np.random.uniform(1, 100, 50)
weights
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(42)
weights = np.random.uniform(1, 100, 50)
plt.figure(figsize=(10, 6))
sns.boxplot(data=weights, color='skyblue')
plt.title('Distribution of Rock Weights')
plt.xlabel('Rocks')
plt.ylabel('Weight')
plt.grid(True)
plt.show()

This exercise aims to create a visually appealing box plot using Python.
The first step involves generating the data.
We use the numpy library to create an array of 50 random weights,
uniformly distributed between 1 and 100.
Next, we import matplotlib.pyplot and seaborn for plotting.
The seaborn library is particularly useful for creating attractive and
informative visualizations.
We set the random seed to ensure reproducibility of the random data.
The plt.figure function sets the size of the plot.
The sns.boxplot function creates the box plot, with the data and color
specified.
We then add a title and labels for the x and y axes to make the plot more
informative.
The plt.grid function adds grid lines to the plot, enhancing its readability.
Finally, plt.show displays the plot.
【Trivia】
‣ Box plots are also known as whisker plots.
‣ They are useful for displaying the distribution of data based on a five-
number summary: minimum, first quartile (Q1), median, third quartile (Q3),
and maximum.
‣ Outliers in the data are often indicated by dots or asterisks outside the
whiskers of the box plot.
65. Generate a Heatmap of a 15x15 Matrix of
Random Values
Importance★★★☆☆
Difficulty★★☆☆☆
You are a data analyst for a company that wants to visualize the distribution
of values within a 15x15 matrix of random numbers.
Your task is to generate a heatmap of this matrix using Python.
The matrix should consist of random values between 0 and 100.
Create the data within your code and produce a visually appealing heatmap.
This exercise focuses on creating visually attractive data visualizations
using Python.
Write code that will generate the heatmap and display it.

【Data Generation Code Example】

import numpy as np
data = np.random.rand(15, 15) * 100
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(15, 15) * 100
plt.imshow(data, cmap='viridis', interpolation='nearest')
plt.colorbar(label='Value')
plt.title('Heatmap of 15x15 Random Values')
plt.show()
This exercise aims to demonstrate how to create visually appealing
heatmaps using Python.
First, we use the NumPy library to generate a 15x15 matrix of random
values between 0 and 100.
The np.random.rand(15, 15) * 100 line generates this matrix.
Next, we use Matplotlib, a powerful plotting library in Python, to create and
display the heatmap.
The plt.imshow function is used to display the matrix as an image, with the
cmap parameter specifying the colormap (in this case, 'viridis', known for
its perceptual uniformity).
The interpolation parameter is set to 'nearest' to display the data without any
interpolation between values.
The plt.colorbar function adds a colorbar to the heatmap, providing a
reference for the values.
Finally, plt.title adds a title to the heatmap, and plt.show displays the plot.
This approach allows you to create informative and visually appealing
heatmaps for any matrix of values.
【Trivia】
‣ Heatmaps are a great way to visualize data distributions and patterns
within a matrix.
‣ The 'viridis' colormap used here is designed to be perceptually uniform,
meaning that equal steps in data are perceived as equal steps in the color
space.
‣ Matplotlib offers a variety of colormaps to choose from, each suitable for
different types of data visualizations.
‣ Heatmaps are widely used in various fields, including biology (e.g.,
displaying gene expression data), finance (e.g., showing correlations
between stocks), and meteorology (e.g., visualizing temperature variations).
66. Creating a 3D Surface Plot in Python
Importance★★★★☆
Difficulty★★★☆☆
A client in the visual arts industry needs to create a visually appealing 3D
surface plot for an upcoming digital art presentation.
Your task is to create a 3D surface plot of the function z=sin⁡(x)⋅exp⁡(−y)z =
\sin(x) \cdot \exp(-y^2)z=sin(x)⋅exp(−y).
The plot should demonstrate high aesthetic quality and artistic value.
Write a Python script that generates this plot using the necessary libraries,
ensuring the output is visually striking.
Do not include any data import/export operations; generate all data within
the script.
Focus on making the plot visually engaging with appropriate customization
of plot elements such as color, lighting, and perspective.

【Data Generation Code Example】

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.exp(-y**2)
【Diagram Answer】

【Code Answer】

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.exp(-y**2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
ax.set_title('3D Surface Plot of z = sin(x) * exp(-y^2)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

This exercise aims to enhance the user's ability to create visually appealing
3D surface plots in Python, emphasizing artistic value.
The plot visualizes the function z=sin⁡(x)⋅exp⁡(−y)z = \sin(x) \cdot \exp(-
y^2)z=sin(x)⋅exp(−y).
The numpy library is used to create a grid of x and y values over a specified
range.
The matplotlib library, along with its mpl_toolkits.mplot3d module, is
utilized to generate and display the 3D plot.
The plot_surface method is used to create the surface plot, with the 'viridis'
colormap chosen for its visual appeal.
Title and axis labels are added to make the plot informative.
The goal is to not only generate the plot but also to ensure it is aesthetically
pleasing by adjusting elements like color and perspective.
This practice helps users learn how to produce high-quality visualizations,
important for applications in digital art and presentations.
【Trivia】
‣ The viridis colormap is designed to be perceptually uniform, making it a
popular choice for scientific visualizations due to its readability for
colorblind individuals.
‣ The exp(-y^2) term in the function z=sin⁡(x)⋅exp⁡(−y)z = \sin(x) \cdot
\exp(-y^2)z=sin(x)⋅exp(−y) creates a Gaussian envelope that modifies the
sine wave, giving the plot a smooth and wavy appearance.
‣ 3D surface plots are commonly used in various fields such as data
science, engineering, and visual arts to represent complex data structures
and mathematical functions in a more intuitive and visually engaging way.
67. Polar Plot of the Function r = 1 + sin(3θ)
Importance★★★☆☆
Difficulty★★☆☆☆
A client is working on a project that involves visualizing complex functions
for an art exhibit.
Your task is to create a polar plot of the function r = 1 + sin(3θ) to help
them present an aesthetically pleasing visualization.
Ensure the plot is visually striking and the code focuses on artistic aspects.
Use appropriate libraries and techniques to enhance the visual appeal.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 + np.sin(3 * theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 + np.sin(3 * theta)
plt.figure(figsize=(8, 8)) #設定されたプロットのサイズを指定
ax = plt.subplot(111, projection='polar') #極座標プロットの作成
ax.plot(theta, r, color='purple', linewidth=2) #プロットの色と線の太さ
を設定
ax.set_title('Polar Plot of $r = 1 + \sin(3\theta)$', va='bottom') #タイトル
を設定
ax.grid(True) #グリッドを表示plt.show()#プロットを表示

To create a visually appealing polar plot of the function r=1+sin⁡(3θ)r = 1 +


\sin(3\theta)r=1+sin(3θ), we start by generating the necessary data.
We use numpy to create an array of θ\thetaθ values ranging from 0 to
2π2\pi2π.
The function r=1+sin⁡(3θ)r = 1 + \sin(3\theta)r=1+sin(3θ) is then applied to
these θ\thetaθ values to get the corresponding rrr values.
The matplotlib library is employed to create the polar plot.
We begin by setting the plot size to make it visually striking and initialize a
polar subplot.
The plot is drawn with a purple line, ensuring it stands out, and the
linewidth is set to make the line prominent.
The title of the plot is added to give context, and the grid is enabled to
enhance the readability and aesthetics of the plot.
The show function is called to display the final plot. This code ensures that
the visualization is not only correct but also artistically appealing.
【Trivia】
‣ The function r=1+sin⁡(3θ)r = 1 + \sin(3\theta)r=1+sin(3θ) creates a three-
petaled rose when plotted in polar coordinates.
‣ Polar plots are particularly useful in fields like physics and engineering to
represent data that has a directional component.
‣ The aesthetic aspect of data visualization can significantly enhance the
interpretability and impact of the presented information, making it a crucial
skill in both scientific and artistic domains.
68. Bar Chart of Monthly Steps by Five People
Importance★★★★☆
Difficulty★★★☆☆
A fitness company wants to visualize the monthly steps taken by five of
their customers to better understand their activity levels. Your task is to
create a bar chart using Python to display the number of steps taken by
these five individuals over a month. This chart should be visually appealing
and focus on artistic quality.Use the following steps data for the
individuals:Person A: 12000, 15000, 13000, 11000, 9000, 16000, 17000,
14000, 10000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000,
26000, 27000, 28000, 29000, 30000, 31000, 32000, 33000, 34000, 35000,
36000, 37000, 38000, 39000Person B: 10000, 11000, 12000, 13000, 14000,
15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000,
25000, 26000, 27000, 28000, 29000, 30000, 31000, 32000, 33000, 34000,
35000, 36000, 37000, 38000, 39000, 40000Person C: 15000, 14000, 13000,
12000, 11000, 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000,
1000, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600,
1700, 1800, 1900, 2000Person D: 9000, 9500, 9000, 8500, 8000, 7500,
7000, 6500, 6000, 5500, 5000, 4500, 4000, 3500, 3000, 2500, 2000, 1500,
1000, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500,
1600Person E: 20000, 19000, 18000, 17000, 16000, 15000, 14000, 13000,
12000, 11000, 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000,
1000, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500Write
Python code to create this bar chart and make sure it is artistically pleasing.
【Data Generation Code Example】

import matplotlib.pyplot as plt


import numpy as np
data = {
"Person A": [12000, 15000, 13000, 11000, 9000, 16000, 17000, 14000,
10000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000,
26000, 27000, 28000, 29000, 30000, 31000, 32000, 33000, 34000,
35000, 36000, 37000, 38000, 39000],
"Person B": [10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000,
18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000,
27000, 28000, 29000, 30000, 31000, 32000, 33000, 34000, 35000,
36000, 37000, 38000, 39000, 40000],
"Person C": [15000, 14000, 13000, 12000, 11000, 10000, 9000, 8000,
7000, 6000, 5000, 4000, 3000, 2000, 1000, 500, 600, 700, 800, 900,
1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000],
"Person D": [9000, 9500, 9000, 8500, 8000, 7500, 7000, 6500, 6000,
5500, 5000, 4500, 4000, 3500, 3000, 2500, 2000, 1500, 1000, 500, 600,
700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600],
"Person E": [20000, 19000, 18000, 17000, 16000, 15000, 14000, 13000,
12000, 11000, 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000,
1000, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500]
}
fig = plt.figure(figsize=(12, 8))
for i, (person, steps) in enumerate(data.items()):
plt.bar(np.arange(len(steps)) + i * 0.15, steps, width=0.15, label=person)
plt.xlabel('Day of the Month')
plt.ylabel('Number of Steps')
plt.title('Steps Taken by 5 Different People Over a Month')
plt.legend()
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import numpy as np
data = { "Person A": [12000, 15000, 13000, 11000, 9000, 16000, 17000,
14000, 10000, 18000, 19000, 20000, 21000, 22000, 23000, 24000,
25000, 26000, 27000, 28000, 29000, 30000, 31000, 32000, 33000,
34000, 35000, 36000, 37000, 38000, 39000],
"Person B": [10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000,
18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000,
27000, 28000, 29000, 30000, 31000, 32000, 33000, 34000, 35000,
36000, 37000, 38000, 39000, 40000],
"Person C": [15000, 14000, 13000, 12000, 11000, 10000, 9000, 8000,
7000, 6000, 5000, 4000, 3000, 2000, 1000, 500, 600, 700, 800, 900,
1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000],
"Person D": [9000, 9500, 9000, 8500, 8000, 7500, 7000, 6500, 6000,
5500, 5000, 4500, 4000, 3500, 3000, 2500, 2000, 1500, 1000, 500, 600,
700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600],
"Person E": [20000, 19000, 18000, 17000, 16000, 15000, 14000, 13000,
12000, 11000, 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000,
1000, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500] }
fig = plt.figure(figsize=(12, 8))
positions = [np.arange(len(data["Person A"])) + i * 0.15 for i in
range(len(data))]
for i, (person, steps) in enumerate(data.items()): plt.bar(positions[i], steps,
width=0.15, label=person)
plt.xlabel('Day of the Month')
plt.ylabel('Number of Steps')
plt.title('Steps Taken by 5 Different People Over a Month')
plt.legend()
plt.show()

To create a visually appealing bar chart comparing the number of steps


taken by five different people over a month, the process involves several
steps.
Firstly, we import the necessary libraries, matplotlib.pyplot for plotting and
numpy for numerical operations.
The data for the steps taken by each person is stored in a dictionary, where
the keys are the names of the people and the values are lists of step counts.
A figure is then created with specific dimensions using plt.figure(figsize=
(12, 8)), which sets the size of the output chart.
To plot the data, we use a loop to iterate through each person’s data. The
positions of the bars are adjusted using np.arange and a calculated offset i *
0.15 to ensure the bars for different people do not overlap but are placed
next to each other. The width parameter in plt.bar controls the thickness of
the bars.
The x-axis is labeled as 'Day of the Month', and the y-axis is labeled as
'Number of Steps'. The chart is given a title 'Steps Taken by 5 Different
People Over a Month'.
Finally, a legend is added to distinguish between the different individuals.
The plt.show() command displays the chart.
This code focuses on creating an aesthetically pleasing and informative
visualization, emphasizing clarity and visual appeal, which is crucial in
'Python Visual Art'. Adjustments in bar positioning, chart size, and proper
labeling contribute to the overall effectiveness of the visualization.
【Trivia】
‣ Matplotlib, used in this example, is one of the most widely used Python
libraries for plotting and has extensive capabilities for creating both simple
and complex visualizations.
‣ Effective visualization is not only about presenting data but also about
ensuring that the information is easily interpretable and visually engaging.
This often involves careful consideration of color schemes, layout, and even
the type of chart used.
‣ In data visualization, bar charts are particularly useful for comparing
quantities across different categories, making them a popular choice for
many types of data analysis.
69. Scatter Plot with Artistic Visuals
Importance★★★☆☆
Difficulty★★★☆☆
A client has requested a visually appealing scatter plot for a presentation.
The plot should contain 1200 points, each with different colors and sizes to
enhance its artistic appeal. Create a Python script that generates this scatter
plot. The data for the points should be generated within the script. Ensure
the plot is aesthetically pleasing and suitable for a high-impact visual
presentation.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
Generate random data for the scatter plot
x = np.random.rand(1200)
y = np.random.rand(1200)
colors = np.random.rand(1200)
sizes = 1000 * np.random.rand(1200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
Generate random data for the scatter plot
x = np.random.rand(1200)
y = np.random.rand(1200)
colors = np.random.rand(1200)
sizes = 1000 * np.random.rand(1200)
Create the scatter plot
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

In this exercise, the goal is to create a scatter plot that is not only functional
but also visually striking. This involves generating random data points and
using different colors and sizes to enhance the visual appeal of the plot. The
numpy library is used to generate random numbers for the x and y
coordinates, colors, and sizes of the points. The matplotlib.pyplot library is
then used to create the scatter plot.
▸ The scatter function from matplotlib.pyplot is used to create the plot,
where:
x and y are the coordinates of the points.
c specifies the colors of the points.
s specifies the sizes of the points.
alpha controls the transparency of the points.
cmap specifies the colormap used for coloring the points.
A color bar is added to provide a reference for the colors used in the plot.
The title and labels for the axes are also added to make the plot more
informative. This exercise helps in understanding how to use matplotlib to
create visually appealing plots that can be used in presentations.
【Trivia】
‣ The viridis colormap used in this plot is designed to be perceptually
uniform, meaning it is easier to interpret and distinguish colors across the
entire range. This makes it a popular choice for scientific visualizations.
‣ Scatter plots are useful for visualizing the relationship between two
variables, and adding variations in color and size can help convey
additional dimensions of data.
‣ The alpha parameter is useful for handling overlapping points by making
them semi-transparent, which can help in visualizing dense data points.
70. Mineral Distribution Pie Chart
Importance★★★★☆
Difficulty★★☆☆☆
You are working with a geological survey team that needs to visualize the
distribution of different types of minerals in a rock sample. Your task is to
create a pie chart that represents the percentage distribution of these
minerals. The data for the mineral types and their respective percentages
will be generated within the code.Write a Python program that generates a
pie chart to visually represent the distribution of the following minerals in a
rock sample:
‣ Quartz: 40%
‣ Feldspar: 30%
‣ Mica: 20%
‣ Other minerals: 10%Ensure that the pie chart is visually appealing and
highlights the different mineral types clearly.

【Data Generation Code Example】

import matplotlib.pyplot as plt


# Data generation
minerals = ['Quartz', 'Feldspar', 'Mica', 'Other minerals']
percentages = [40, 30, 20, 10]
# Pie chart creation code
plt.figure(figsize=(8, 8))
plt.pie(percentages, labels=minerals, autopct='%1.1f%%', startangle=140)
plt.title('Mineral Distribution in Rock Sample')
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


# Data generation
minerals = ['Quartz', 'Feldspar', 'Mica', 'Other minerals']
percentages = [40, 30, 20, 10]
# Pie chart creation code
plt.figure(figsize=(8, 8)) # Set the figure size
plt.pie(percentages, labels=minerals, autopct='%1.1f%%', startangle=140,
# Add labels, percentage, and start angle
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99'],
# Use custom colors for each section
wedgeprops={'edgecolor': 'black'})
# Add edge color to the wedges
plt.title('Mineral Distribution in Rock Sample')
# Add title to the pie chart
plt.show()
# Display the pie chart

The goal of this exercise is to create a visually appealing pie chart that
represents the distribution of different minerals in a rock sample using
Python's Matplotlib library.
The code begins by importing the Matplotlib library, which is essential for
creating visualizations in Python. We then define two lists: minerals and
percentages. The minerals list contains the names of the mineral types, and
the percentages list contains their corresponding percentage distributions.
To create the pie chart, we use plt.figure(figsize=(8, 8)) to set the size of the
figure to 8x8 inches, making it large enough to be clearly visible. The
plt.pie function is used to generate the pie chart, where we pass the
percentages list to define the size of each slice, and the labels parameter to
assign names to each slice. The autopct='%1.1f%%' argument formats the
percentage values to one decimal place, and startangle=140 rotates the chart
to start from an angle of 140 degrees for better visual appeal.
To enhance the chart's aesthetics, we use the colors parameter to assign
custom colors to each slice and the wedgeprops parameter to add a black
edge color to the slices. Finally, plt.title('Mineral Distribution in Rock
Sample') adds a title to the chart, and plt.show() displays the pie chart.
This exercise not only demonstrates how to create a pie chart but also
emphasizes the importance of making visualizations aesthetically pleasing
and easy to interpret. By adjusting colors, edge properties, and formatting
options, we can create a professional and informative chart.
【Trivia】
The pie chart was first used by William Playfair in 1801. He is considered
one of the pioneers of information graphics, and his work laid the
foundation for many modern charting techniques. Pie charts are best used
for displaying parts of a whole, but they can become less effective when
dealing with a large number of categories or when the differences between
categories are small. In such cases, bar charts or other types of
visualizations might be more appropriate.
71. Building Heights Histogram Visualization
Importance★★★☆☆
Difficulty★★☆☆☆
A construction company wants to visualize the distribution of the heights of
buildings they have constructed in various cities.
They have data on 200 different buildings, and they would like to see this
data represented in a histogram to better understand the height distribution.
Using Python, generate synthetic data for the heights of these 200 buildings
and create a visually appealing histogram to represent this data.
The visualization should focus on artistic aesthetics while effectively
conveying the data distribution.
Ensure that your code generates the data and produces the histogram in a
single run.
Do not use any file I/O operations.

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
heights=np.random.normal(150,30,200)
heights=heights[heights>0]
heights=heights[:200]
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
heights=np.random.normal(150,30,200)
heights=heights[heights>0]
heights=heights[:200]
plt.figure(figsize=(12,6))
plt.hist(heights,bins=20,color='skyblue',edgecolor='black')
plt.title('Distribution of Building Heights',fontsize=20,fontweight='bold')
plt.xlabel('Height (meters)',fontsize=15)
plt.ylabel('Frequency',fontsize=15)
plt.grid(axis='y',alpha=0.75)
plt.axvline(x=np.mean(heights),color='red',linestyle='--',label=f'Mean:
{np.mean(heights):.2f}m')
plt.legend(fontsize=12)
plt.show()

This exercise is designed to combine data visualization skills with an


artistic approach to creating visually appealing plots.
The goal is to generate a histogram that not only accurately represents the
data but also stands out due to its aesthetic quality.
First, we use the numpy library to create synthetic data for the heights of
200 buildings. We use a normal distribution centered around 150 meters
with a standard deviation of 30 meters. By setting a random seed, we ensure
the reproducibility of our data. We then filter out any negative values
(though unlikely in this context) and ensure we have exactly 200 data
points.In the plotting section, we use matplotlib to create the histogram. The
figsize parameter adjusts the size of the figure for better visibility. The color
'skyblue' is chosen for the bars, with 'black' edges to enhance clarity. Titles
and labels are styled to be bold and larger in font size for better
readability.The grid and mean line add both an aesthetic touch and valuable
information. The grid lines, controlled by the alpha parameter for
transparency, help viewers track the frequencies more easily. The vertical
mean line, colored red and dashed, highlights the average height of the
buildings, with a label showing the exact mean value.This combination of
functional and aesthetic elements helps make the histogram both
informative and visually engaging. It demonstrates how data visualization
can be turned into an art form while still serving its primary purpose of data
representation.
【Trivia】
‣ The choice of colors in data visualization can significantly impact
readability and viewer engagement. Light colors with contrasting edges are
often used for better clarity.
‣ Adding grid lines and statistical markers like mean lines can enhance the
informative value of a plot. They provide additional context and make it
easier for viewers to interpret the data.
‣ Matplotlib, used in this exercise, is one of the most widely used libraries
for data visualization in Python. It offers a great balance between simplicity
and customization.
72. Box Plot for Bridge Lengths
Importance★★★☆☆
Difficulty★★☆☆☆
A construction company is analyzing the lengths of 50 different bridges to
understand their distribution.
Your task is to create a box plot to visually represent the distribution of
these bridge lengths.
Generate random data for the bridge lengths within a reasonable range and
create a box plot using Python.
Ensure the plot is artistically appealing, as the company values aesthetics
highly in their presentations.

【Data Generation Code Example】

import numpy as np
np.random.seed(0) # For reproducibility
bridge_lengths = np.random.randint(100, 1000, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0) # For reproducibility
bridge_lengths = np.random.randint(100, 1000, 50)
plt.figure(figsize=(10, 6))
plt.boxplot(bridge_lengths, patch_artist=True,
boxprops=dict(facecolor='lightblue', color='blue'),
whiskerprops=dict(color='blue'),
capprops=dict(color='blue'),
medianprops=dict(color='red'),
flierprops=dict(marker='o', color='red', alpha=0.5))
plt.title('Distribution of Bridge Lengths')
plt.ylabel('Length (meters)')
plt.grid(True)
plt.show()

In this exercise, you will create a box plot to display the distribution of
bridge lengths.
The goal is to not only generate the plot but also ensure it is visually
appealing, as the company places a high value on aesthetics.
First, you generate random bridge lengths using NumPy's randint function.
The lengths are set to range between 100 and 1000 meters to represent
typical bridge sizes. This data generation is done with a fixed random seed
for reproducibility.
▸ Next, using Matplotlib, you create a box plot. To enhance the visual
appeal, the box plot is customized:
‣ The patch_artist=True parameter allows you to fill the boxes with color.
‣ The boxprops, whiskerprops, capprops, medianprops, and flierprops
dictionaries are used to customize the colors of the box plot components.
For instance, the boxes are filled with light blue, the median is highlighted
in red, and the outliers (fliers) are marked with red circles.
‣ Finally, the title and y-axis label are added, and a grid is enabled for
better readability. The figure(figsize=(10, 6)) line ensures the plot is large
enough for presentations.
By following these steps, you not only create an informative plot but also
enhance its visual appeal, aligning with the company's emphasis on
aesthetics.
【Trivia】
The box plot, also known as a whisker plot, was introduced by John Tukey
in his book "Exploratory Data Analysis" in 1977. It is a standardized way of
displaying the distribution of data based on a five-number summary:
minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
This type of plot is particularly useful for identifying outliers and
understanding the spread and skewness of the data.
73. Generate a Heatmap of a 16x16 Matrix of
Random Values
Importance★★★★☆
Difficulty★★☆☆☆
You are a data visualization specialist tasked with creating an artistic
representation of a 16x16 matrix of random values for a client's
presentation. The client wants the heatmap to be visually appealing and
artistic. Use Python to generate the heatmap and ensure that the
visualization is aesthetically pleasing. The input data should be generated
within the code.
【Data Generation Code Example】

import numpy as np
data = np.random.rand(16, 16)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(16, 16)
plt.figure(figsize=(10, 8))
sns.heatmap(data, cmap='viridis', cbar=True, linewidths=.5, annot=False)
plt.title('Artistic Heatmap of Random Values')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create a visually appealing heatmap, we first import the necessary


libraries: numpy for generating random data, matplotlib.pyplot for plotting,
and seaborn for creating the heatmap.
We generate a 16x16 matrix of random values using np.random.rand(16,
16). This matrix serves as our input data.
We then set up the plot with plt.figure(figsize=(10, 8)) to ensure the
heatmap has a good size for presentation. The sns.heatmap function is used
to create the heatmap, with the cmap='viridis' parameter providing a
visually appealing color map. The cbar=True parameter adds a color bar to
the heatmap, and linewidths=.5 adds thin lines between the cells for better
visual separation. The annot=False parameter ensures that the cells are not
annotated with their values, maintaining a clean look.
Finally, we add a title and labels to the axes with plt.title, plt.xlabel, and
plt.ylabel, and display the plot using plt.show(). This results in an
aesthetically pleasing heatmap suitable for the client's presentation.
【Trivia】
‣ The viridis colormap is often preferred for heatmaps because it is
perceptually uniform, meaning it looks good and is easy to interpret across
a wide range of devices and viewing conditions.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive and informative statistical graphics.
‣ Heatmaps are a great way to visualize the magnitude of data across a two-
dimensional space, making them ideal for showing patterns, correlations,
and outliers in data.
74. 3D Surface Plot of z = cos(x) * exp(-y^2)
Importance★★★☆☆
Difficulty★★★☆☆
A client is working on a project that involves visualizing complex
mathematical functions to create aesthetically pleasing and informative
graphics. They need a 3D surface plot of the function
z=cos⁡(x)⋅exp⁡(−y)z=\cos(x)\cdot \exp(-y^2)z=cos(x)⋅exp(−y) to be
generated using Python. The goal is to create a visually stunning
representation of this function.
Write a Python script that generates this 3D surface plot. The script should
be able to create the data for the plot within itself and then display the plot.
Ensure that the plot is visually appealing with appropriate labels, color
schemes, and other artistic elements.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.exp(-Y**2)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.exp(-Y**2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title('3D Surface Plot of z = cos(x) * exp(-y^2)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

To create a visually appealing 3D surface plot of the function


z=cos⁡(x)⋅exp⁡(−y)z=\cos(x)\cdot \exp(-y^2)z=cos(x)⋅exp(−y), we start by
importing the necessary libraries: NumPy for numerical operations and
Matplotlib for plotting.
First, we generate the data for the plot. We create a range of values for xxx
and yyy using np.linspace, which generates evenly spaced values over a
specified range. Here, we generate 100 values between -5 and 5 for both
xxx and yyy.
Next, we create a meshgrid using np.meshgrid, which creates a grid of xxx
and yyy values. This grid will be used to compute the corresponding zzz
values using the given function z=cos⁡(x)⋅exp⁡(−y)z=\cos(x)\cdot \exp(-
y^2)z=cos(x)⋅exp(−y).
For the plotting part, we create a figure and a 3D axis using Matplotlib. The
plot_surface method is used to create the 3D surface plot, with the cmap
parameter set to 'viridis' to apply a visually appealing color map. We then
set the title and labels for the axes to make the plot informative. Finally, we
display the plot using plt.show().
This process ensures that the generated plot is not only accurate but also
visually attractive, fulfilling the client's requirement for a beautiful visual
representation of the mathematical function.
【Trivia】
‣ The viridis colormap used in this example is designed to be perceptually
uniform, meaning that the perceived differences in color are consistent
across the range, making it an excellent choice for scientific visualizations.
‣ The plot_surface method in Matplotlib allows for extensive
customization, including lighting effects, which can further enhance the
visual appeal of 3D plots.
‣ The exponential function exp⁡(−y)\exp(-y^2)exp(−y) ensures that the
values of zzz decay rapidly as yyy moves away from zero, creating a bell-
shaped surface when combined with the cosine function. This characteristic
is often used in Gaussian functions and probability distributions.
75. Polar Plot of r = sin(5θ)
Importance★★★☆☆
Difficulty★★☆☆☆
A client wants to create an artistic representation of a mathematical function
for their new design project. They have chosen the polar function
r=sin⁡(5θ)r=\sin(5\theta)r=sin(5θ) and need a visually appealing plot using
Python. The plot should be aesthetically pleasing and suitable for use in a
design context.
Write a Python program that generates and displays a polar plot of the
function r=sin⁡(5θ)r=\sin(5\theta)r=sin(5θ). Ensure the plot is visually
appealing by using appropriate colors and styles.
Use the following code to generate the input data for the plot.

【Data Generation Code Example】

import numpy as np
theta = np.linspace(0, 2 * np.pi, 1000)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.sin(5 * theta)
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='magenta', linewidth=2)
ax.set_facecolor('black')
ax.grid(color='white', linestyle='--', linewidth=0.5)
ax.set_title('Polar Plot of r = sin(5θ)', color='white', fontsize=20)
plt.show()

To create a visually appealing polar plot of the function


r=sin⁡(5θ)r=\sin(5\theta)r=sin(5θ), we first generate the input data.
We use NumPy to create an array of θ\theta θ values ranging from 0 to
2π2\pi 2π. This ensures we cover the full range of angles for a complete
plot.
Next, we calculate the corresponding rrr values using the function
r=sin⁡(5θ)r=\sin(5\theta)r=sin(5θ).
For the plot, we use Matplotlib's polar projection. We set the figure size to
make the plot large and clear.
We then plot the data with a magenta line of width 2 for better visibility. To
enhance the aesthetics, we set the background color of the plot to black and
the grid lines to white with a dashed style.
Finally, we add a title to the plot, setting its color to white and increasing
the font size for readability. This creates an artistic and visually appealing
representation of the function.
【Trivia】
‣ Polar plots are useful for representing data that has a directional
component, such as wind directions or signal strengths.
‣ The function r=sin⁡(5θ)r=\sin(5\theta)r=sin(5θ) creates a five-petaled
flower-like pattern known as a rose curve. This is a type of sinusoidal
spiral.
‣ Matplotlib's polar plotting capabilities allow for easy visualization of
such functions, making it a powerful tool for both scientific and artistic
purposes.
76. Museum Visitors Bar Chart
Importance★★★★☆
Difficulty★★★☆☆
You are a data analyst working for a cultural institution that manages
several museums. Your manager has asked you to create a visually
appealing bar chart to compare the number of visitors to 5 different
museums over a year. The chart should be artistically designed to make it
engaging and informative.
Generate the input data within your code and ensure the chart is visually
attractive.

【Data Generation Code Example】

import numpy as np
import pandas as pd
museums = ['Museum A', 'Museum B', 'Museum C', 'Museum D',
'Museum E']
visitors = np.random.randint(5000, 50000, size=5)
data = pd.DataFrame({'Museum': museums, 'Visitors': visitors})
【Diagram Answer】

【Code Answer】

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
museums = ['Museum A', 'Museum B', 'Museum C', 'Museum D',
'Museum E']
visitors = np.random.randint(5000, 50000, size=5)
data = pd.DataFrame({'Museum': museums, 'Visitors': visitors})
plt.figure(figsize=(10, 6))
sns.barplot(x='Museum', y='Visitors', data=data, palette='viridis')
plt.title('Annual Visitors to Museums', fontsize=16)
plt.xlabel('Museum', fontsize=14)
plt.ylabel('Number of Visitors', fontsize=14)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.grid(True, which='both', linestyle='--', linewidth=0.5)
plt.show()

To create a visually appealing bar chart comparing the number of visitors to


5 different museums over a year, we use Python libraries such as Matplotlib
and Seaborn.
First, we generate random data for the number of visitors using NumPy and
store it in a pandas DataFrame. This data represents the annual visitors to
each museum.
Next, we set up the plot using Matplotlib and Seaborn. We create a bar plot
with the 'Museum' names on the x-axis and the 'Visitors' count on the y-
axis. The 'viridis' palette is chosen for its visually appealing color gradient.
We then add titles and labels with appropriate font sizes to enhance
readability. The grid lines are added to make the chart more informative.
Finally, we display the chart using plt.show(), ensuring it is both
informative and artistically engaging.
【Trivia】
‣ Seaborn is a Python data visualization library based on Matplotlib that
provides a high-level interface for drawing attractive and informative
statistical graphics.
‣ The 'viridis' color palette is designed to be perceptually uniform, meaning
it is easy to interpret and distinguish between different colors, making it
ideal for visualizations.
‣ Adding grid lines in a plot can help viewers better understand the data by
providing reference points.
77. Scatter Plot with Artistic Flair
Importance★★★☆☆
Difficulty★★★☆☆
You are a data visualization expert working for a design agency. A client
has requested a visually striking scatter plot to be used in their upcoming
marketing campaign. The scatter plot should contain 1300 points, each with
different colors and sizes to create an artistic effect. Generate the data
within the code and produce a scatter plot that meets these requirements.
Ensure the plot is both visually appealing and informative.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(1300)
y = np.random.rand(1300)
colors = np.random.rand(1300)
sizes = 1000 * np.random.rand(1300)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(1300)
y = np.random.rand(1300)
colors = np.random.rand(1300)
sizes = 1000 * np.random.rand(1300)
plt.figure(figsize=(10, 6))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Artistic Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

To create an artistic scatter plot in Python, we use the matplotlib library,


which is widely used for data visualization.
First, we import the necessary libraries: numpy for generating random data
and matplotlib.pyplot for plotting.
We set a random seed using np.random.seed(0) to ensure reproducibility of
the random data. This means that every time the code is run, the same
random numbers will be generated.
Next, we generate 1300 random points for the x and y coordinates using
np.random.rand(1300). This function generates random numbers between 0
and 1.
We then create arrays for colors and sizes. The colors array is also
generated using np.random.rand(1300), which will provide a different
random color for each point. The sizes array is generated using 1000 *
np.random.rand(1300), which scales the random numbers to be between 0
and 1000, giving a variety of sizes to the points.
In the plotting section, we create a figure with a specified size using
plt.figure(figsize=(10, 6)). This sets the dimensions of the plot.
We then use plt.scatter to create the scatter plot. The c parameter is set to
the colors array, the s parameter to the sizes array, alpha is set to 0.5 to
make the points semi-transparent, and cmap is set to 'viridis' to use a
specific colormap. The plt.colorbar() function adds a color bar to the plot,
which helps in understanding the color distribution.
Finally, we add a title and labels to the axes using plt.title, plt.xlabel, and
plt.ylabel, and display the plot with plt.show(). This results in a visually
striking scatter plot with varying colors and sizes, suitable for the client's
marketing campaign.
【Trivia】
‣ The matplotlib library was originally developed by John D. Hunter in
2003 and has since become one of the most popular plotting libraries in
Python.
‣ The viridis colormap used in this example is designed to be perceptually
uniform, meaning that it is easy to interpret the data visually. It is also
colorblind-friendly.
‣ Scatter plots are not only useful for visualizing data but can also be used
creatively in design and art, as demonstrated in this exercise.
78. Pie Chart of Quarry Rock Distribution
Importance★★★★☆
Difficulty★★☆☆☆
A quarry company wants to visualize the distribution of different types of
rocks extracted from their site.
They have categorized the rocks into five types: Granite, Limestone,
Marble, Sandstone, and Slate.
Your task is to create a pie chart that artistically represents the distribution
of these rocks.
The data for the rock distribution is as follows: Granite - 25%, Limestone -
20%, Marble - 15%, Sandstone - 30%, Slate - 10%.
Create a Python script to generate this pie chart with a focus on visual
aesthetics.

【Data Generation Code Example】

import matplotlib.pyplot as plt


rock_types = ['Granite', 'Limestone', 'Marble', 'Sandstone', 'Slate']
distribution = [25, 20, 15, 30, 10]
plt.figure(figsize=(8, 8))
plt.pie(distribution, labels=rock_types, autopct='%1.1f%%',
startangle=140, colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'])
plt.axis('equal')
plt.show()
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


rock_types = ['Granite', 'Limestone', 'Marble', 'Sandstone', 'Slate']
distribution = [25, 20, 15, 30, 10]
plt.figure(figsize=(8, 8))
plt.pie(distribution, labels=rock_types, autopct='%1.1f%%',
startangle=140, colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'],
pctdistance=0.85, wedgeprops={'edgecolor': 'black'})
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.axis('equal')
plt.title('Rock Distribution in Quarry')
plt.show()

To create a visually appealing pie chart in Python, we use the matplotlib


library, which is a powerful tool for creating a wide range of static,
animated, and interactive visualizations.
First, we import the necessary library, matplotlib.pyplot, which provides a
MATLAB-like interface.
Next, we define the data for our pie chart. The rock_types list contains the
names of the different types of rocks, and the distribution list contains their
respective percentages.
We then create a figure with a specified size using plt.figure(figsize=(8, 8)).
This ensures that our pie chart has enough space and is not cramped.
The plt.pie() function is used to create the pie chart. We pass the
distribution data and the labels for each slice. The autopct parameter is used
to display the percentage value on each slice, formatted to one decimal
place. The startangle parameter rotates the start of the pie chart for better
visual balance. We also specify custom colors for each slice using the colors
parameter.
To enhance the visual appeal, we add a white circle at the center of the pie
chart to create a donut-like appearance. This is done by creating a Circle
object and adding it to the current figure using fig.gca().add_artist(). This
technique is often used in data visualization to make the chart more
readable and aesthetically pleasing.
Finally, we use plt.axis('equal') to ensure that the pie chart is drawn as a
circle, and plt.title() to add a title to our chart. The plt.show() function is
called to display the chart.
This approach not only creates a functional pie chart but also emphasizes
artistic elements, making the visualization more engaging and informative.
【Trivia】
‣ The pie chart was invented by William Playfair in 1801.
‣ Matplotlib was created by John D. Hunter in 2003 and has since become
one of the most widely used plotting libraries in Python.
‣ Adding a central circle to create a donut chart can help improve the
readability of the data by focusing the viewer's attention on the proportions
rather than the area.
‣ The choice of colors in a pie chart is crucial for both aesthetics and
accessibility; it's important to choose colors that are distinguishable by all
viewers, including those with color blindness.
79. Vegetable Weight Histogram
Importance★★★☆☆
Difficulty★★★☆☆
You are working for a grocery store chain and need to analyze the
distribution of vegetable weights to optimize packaging.
Create a histogram of the weights of 200 different vegetables using Python.
The histogram should be visually appealing and artistic, emphasizing
aesthetic elements.
Generate the vegetable weight data within the code.

【Data Generation Code Example】

import numpy as np
weights = np.random.normal(loc=200, scale=50, size=200)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
weights = np.random.normal(loc=200, scale=50, size=200)
plt.figure(figsize=(10, 6))
sns.histplot(weights, bins=30, kde=True, color='green', edgecolor='black')
plt.title('Distribution of Vegetable Weights', fontsize=20,
fontweight='bold')
plt.xlabel('Weight (grams)', fontsize=15)
plt.ylabel('Frequency', fontsize=15)
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

In this exercise, we are focusing on creating a visually appealing histogram


using Python.
We use the numpy library to generate random vegetable weights, assuming
a normal distribution with a mean of 200 grams and a standard deviation of
50 grams.
The seaborn library is used to create the histogram because it offers
enhanced visualization capabilities compared to basic matplotlib.
We set the figure size to 10x6 inches for better visibility.
The sns.histplot function is used to plot the histogram, with 30 bins for a
detailed distribution view.
We enable the kernel density estimate (KDE) to smooth the histogram
curve, adding an artistic touch.
The histogram bars are colored green with black edges to enhance visual
contrast.
Titles and labels are added with increased font sizes and bold styling for
emphasis.
A grid with dashed lines and slight transparency is included to improve
readability and aesthetics.
The final plot is displayed using plt.show().
【Trivia】
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive statistical graphics.
‣ Kernel Density Estimation (KDE) is a non-parametric way to estimate the
probability density function of a random variable, which helps in
visualizing the distribution of data.
‣ The choice of colors and styles in data visualization can significantly
impact the readability and interpretability of the plot.
80. Skyscraper Heights Distribution Visualization
Importance★★★★☆
Difficulty★★★☆☆
A real estate company is interested in understanding the distribution of the
heights of skyscrapers in a major city.
They have collected the heights of 50 different skyscrapers and want to
visualize this data using a box plot.
Your task is to create a Python script that generates a box plot of the
distribution of these heights.
The data should be created within the script.
Ensure that the visualization is aesthetically pleasing and emphasizes the
artistic aspect of data visualization.

【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
heights = np.random.randint(150, 450, 50)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
heights = np.random.randint(150, 450, 50)
fig, ax = plt.subplots(figsize=(10, 6))
ax.boxplot(heights, patch_artist=True,
boxprops=dict(facecolor='skyblue', color='navy'),
whiskerprops=dict(color='navy'),
capprops=dict(color='navy'),
medianprops=dict(color='red'))
ax.set_title('Distribution of Skyscraper Heights', fontsize=16,
fontweight='bold')
ax.set_ylabel('Height (meters)', fontsize=14)
ax.set_xticks([])
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

To create a visually appealing box plot in Python, we use the matplotlib


library.
First, we import the necessary libraries: numpy for generating random data
and matplotlib.pyplot for plotting.
We generate 50 random heights between 150 and 450 meters using
np.random.randint.
The core of the visualization is the ax.boxplot function, which creates the
box plot.
We enhance the visual appeal by setting the patch_artist=True parameter,
which allows us to fill the box with color.
▸ We customize the colors of various elements:
‣ boxprops to set the face color and edge color of the box.
‣ whiskerprops to set the color of the whiskers.
‣ capprops to set the color of the caps.
‣ medianprops to set the color of the median line.
The plot's title and y-axis label are set using ax.set_title and ax.set_ylabel,
respectively, with increased font size and bold formatting for emphasis.
We remove the x-axis ticks using ax.set_xticks([]) to keep the focus on the
box plot itself.
Finally, we add a grid with plt.grid to make the plot easier to read, using a
dashed line style and slight transparency.
The plt.show() function displays the plot.
【Trivia】
Box plots, also known as whisker plots, are a standardized way of
displaying the distribution of data based on a five-number summary:
minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
They are particularly useful for identifying outliers and understanding the
spread and skewness of the data.
81. Heatmap of Random 17x17 Matrix
Importance★★★☆☆
Difficulty★★★☆☆
You are tasked with creating a visually appealing heatmap using Python.
The heatmap should represent a 17x17 matrix filled with random values.
This exercise emphasizes the artistic aspect of data visualization, so the
final output should be aesthetically pleasing. Ensure that the code generates
the data within the script and that all necessary imports are included. The
heatmap should be displayed in English.
【Data Generation Code Example】

import numpy as np
data = np.random.rand(17, 17)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.rand(17, 17)
plt.figure(figsize=(10, 8))
sns.heatmap(data, cmap='viridis', annot=False, cbar=True, linewidths=.5,
linecolor='white')
plt.title('Heatmap of Random 17x17 Matrix')
plt.show()

To create a visually appealing heatmap of a 17x17 matrix filled with


random values, we first import the necessary libraries: numpy for
generating the random data, matplotlib.pyplot for plotting, and seaborn for
creating the heatmap.
We generate the random data using numpy's rand function, which creates a
17x17 matrix of random values between 0 and 1. This matrix serves as our
input data for the heatmap.
Next, we set up the plot using matplotlib's figure function, specifying the
figure size to ensure the heatmap is large enough to be visually appealing.
We then use seaborn's heatmap function to create the heatmap. The cmap
parameter is set to 'viridis', a popular colormap that provides a visually
pleasing gradient of colors. The annot parameter is set to False to avoid
annotating each cell with its value, keeping the heatmap clean. The cbar
parameter is set to True to include a color bar, which helps interpret the
values represented by the colors. The linewidths and linecolor parameters
are used to add white grid lines between the cells, enhancing the visual
separation of the data points.
Finally, we add a title to the heatmap using plt.title and display the plot
using plt.show. This completes the creation of the heatmap, ensuring it is
both informative and artistically appealing.
【Trivia】
‣ The 'viridis' colormap used in this example was designed to be
perceptually uniform, meaning that equal steps in data are perceived as
equal steps in color space. This makes it ideal for accurately representing
data in visualizations.
‣ Seaborn is built on top of Matplotlib and provides a high-level interface
for drawing attractive statistical graphics. It simplifies the process of
creating complex visualizations and enhances the aesthetics of the plots.
‣ Heatmaps are commonly used in various fields such as biology (e.g., to
visualize gene expression data), finance (e.g., to show correlations between
stocks), and sports analytics (e.g., to display player performance metrics).
82. 3D Surface Plot of a Mathematical Function
Importance★★★☆☆
Difficulty★★★☆☆
You are working as a data visualization specialist for a company that wants
to create visually appealing and artistic representations of mathematical
functions for their marketing materials.
Your task is to create a 3D surface plot of the function
z=sin⁡(x)⋅cos⁡(y)z=\sin(x^2)\cdot \cos(y^2)z=sin(x)⋅cos(y).
The plot should be visually stunning and emphasize artistic elements.
Ensure that the plot is clear and aesthetically pleasing.
Use Python to generate the plot.

【Data Generation Code Example】

import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title('3D Surface Plot of z = sin(x^2) * cos(y^2)')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

▸ To create a visually appealing 3D surface plot of the function


z=sin⁡(x)⋅cos⁡(y)z=\sin(x^2)\cdot \cos(y^2)z=sin(x)⋅cos(y) using Python,
follow these steps:
Import Necessary Libraries: Import numpy for numerical operations,
matplotlib.pyplot for plotting, and mpl_toolkits.mplot3d for 3D plotting
capabilities. These libraries provide the tools needed to create detailed and
artistic plots.
Generate Data: Use numpy.linspace to create an array of values for the x
and y axes ranging from -5 to 5 with 100 points each. This range ensures
that the plot captures the full behavior of the function. The numpy.meshgrid
function creates a grid of x and y values, which is essential for plotting the
surface. The function z=sin⁡(x)⋅cos⁡(y)z=\sin(x^2)\cdot
\cos(y^2)z=sin(x)⋅cos(y) is then applied to these grids to generate the z
values.
Create the Plot: Initialize a figure and a 3D subplot using plt.figure() and
fig.add_subplot. The projection='3d' argument is crucial for enabling 3D
plotting. The ax.plot_surface method is used to plot the surface, with the
cmap='viridis' argument specifying the colormap, which enhances the
visual appeal. The colormap 'viridis' is chosen for its aesthetic gradient.
Enhance Aesthetics: Set the title and axis labels using ax.set_title,
ax.set_xlabel, ax.set_ylabel, and ax.set_zlabel. These labels provide context
and make the plot more informative. The overall goal is to create a plot that
is not only informative but also visually striking, suitable for marketing
materials.
Display the Plot: Finally, use plt.show() to display the plot. This function
renders the plot in a window, allowing you to see the final result.
By following these steps, you can create a 3D surface plot that is both
informative and artistically appealing, suitable for various professional and
marketing applications.
【Trivia】
‣ The viridis colormap, used in the plot, is a perceptually uniform
colormap, meaning it is designed to be perceived equally across its range.
This makes it an excellent choice for creating visually appealing and
accurate plots.
‣ The mpl_toolkits.mplot3d library is an extension of Matplotlib that
provides tools for 3D plotting. It is widely used in scientific and
engineering applications for visualizing complex data.
‣ The numpy.meshgrid function is a powerful tool for creating coordinate
matrices. It is often used in conjunction with plotting functions to generate
the necessary grid of points for surface and contour plots.
83. Polar Plot of r = 1 - cos(3θ)
Importance★★★★☆
Difficulty★★★☆☆
A client wants to visualize a unique and artistic representation of a polar
function for a design project. They have provided the function r=1−cos⁡(3θ)r
= 1 - \cos(3\theta)r=1−cos(3θ) and need a Python script that generates this
polar plot with a focus on creating visually appealing art.Your task is to
write a Python script that generates this polar plot. The primary goal is to
create a visually artistic representation of the function, not just a simple
plot. Ensure the plot has artistic elements, such as customized colors and
styles.
【Data Generation Code Example】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 - np.cos(3 * theta)
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
r = 1 - np.cos(3 * theta)
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='purple', linewidth=2)
ax.set_facecolor('black')
ax.grid(color='white', linestyle='--', linewidth=0.5)
ax.set_rticks([]) # Remove radial ticks
ax.set_yticklabels([]) # Remove radial labels
ax.set_xticklabels([]) # Remove angular labels
plt.title('Artistic Polar Plot of r = 1 - cos(3θ)', color='white')
plt.show()

To create an artistic polar plot of the function r=1−cos⁡(3θ)r = 1 -


\cos(3\theta)r=1−cos(3θ), we first import the necessary libraries, numpy and
matplotlib.
We generate theta values ranging from 0 to 2π2\pi2π and calculate the
corresponding r values using the given function.
Next, we create a polar plot using matplotlib.
We set the figure size to 8x8 inches to make the plot large and clear.
We use the 'polar' projection for the subplot to ensure it is a polar plot.
We plot the theta and r values with a purple line of width 2 for a bold
appearance.
To enhance the artistic feel, we set the background color of the plot to black
and use white dashed lines for the grid.
We remove the radial ticks and labels, as well as the angular labels, to
maintain a clean look.
Finally, we add a title with a white color to match the artistic theme.
The overall effect is a visually striking and artistic representation of the
polar function.
【Trivia】
‣ The function r=1−cos⁡(3θ)r = 1 - \cos(3\theta)r=1−cos(3θ) is known as a
three-leaved rose or trefoil.
‣ Polar plots are often used in fields like physics, engineering, and art to
represent data in a circular format.
‣ The use of customized colors and styles in plotting can significantly
enhance the visual appeal and interpretability of data.
84. Artistic Network Visualization with Python
Importance★★★★☆
Difficulty★★★☆☆
A client wants to visualize a network graph that represents the relationships
between different entities.
The graph should be visually appealing and artistic.
Your task is to create a Python script that generates a network graph with 60
nodes and 65 edges.
The visualization should focus on artistic elements, making the graph not
only informative but also aesthetically pleasing.
Ensure that the nodes and edges are styled creatively.
Use the provided code to generate the input data within your script.

【Data Generation Code Example】

import networkx as nx
import random
G = nx.gnm_random_graph(60, 65)
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


import networkx as nx
import random
G = nx.gnm_random_graph(60, 65)
pos = nx.spring_layout(G) # Position nodes using Fruchterman-Reingold
force-directed algorithm
plt.figure(figsize=(12, 12))
nx.draw_networkx_nodes(G, pos, node_size=500, node_color='skyblue',
edgecolors='black', linewidths=2) # Draw nodes with skyblue color and
black edges
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray',
style='dashed') # Draw edges with gray color and dashed style
labels = {i: f'Node {i}' for i in G.nodes()} # Create labels for nodes
nx.draw_networkx_labels(G, pos, labels, font_size=12,
font_color='darkred') # Draw labels with dark red color
plt.title('Artistic Network Graph', fontsize=20, color='navy') # Set title
with navy color
plt.axis('off') # Turn off the axis
plt.show() # Display the graph

To create an artistic network graph, we first generate a random graph with


60 nodes and 65 edges using NetworkX.
We use the spring_layout to position the nodes in a visually appealing
manner, leveraging the Fruchterman-Reingold force-directed algorithm.
This algorithm positions nodes in such a way that all the edges are of more
or less equal length and nodes that are not connected are positioned far from
each other, making the graph look balanced and aesthetically pleasing.
We then use Matplotlib to draw the graph.
The draw_networkx_nodes function is used to draw the nodes with a
skyblue color and black edges, making them stand out.
The draw_networkx_edges function draws the edges with a gray color and
dashed style, adding an artistic touch.
Labels are created for each node using a dictionary comprehension and are
drawn with a dark red color using the draw_networkx_labels function.
The title of the graph is set with a navy color to match the artistic theme.
Finally, the axis is turned off to give a cleaner look to the graph.
This approach ensures that the graph is not only informative but also
visually appealing, meeting the client's requirement for an artistic network
visualization.
【Trivia】
‣ The Fruchterman-Reingold algorithm, used for the spring_layout, is a
force-directed algorithm that simulates a physical system to position nodes
in a graph.
‣ NetworkX is a powerful library for the creation, manipulation, and study
of complex networks of nodes and edges.
‣ Matplotlib is a widely used plotting library in Python, known for its
flexibility and extensive customization options.
‣ Artistic visualizations can enhance the interpretability and engagement of
data presentations, making complex information more accessible.
85. Bar Chart for Trees Planted by Organizations
Importance★★★☆☆
Difficulty★★★☆☆
A city council wants to compare the efforts of different environmental
organizations in planting trees over the past year. They need a bar chart that
visually represents the number of trees planted by five different
organizations. Create a Python script that generates this bar chart.Use the
following data for the number of trees planted:Organization A:
120Organization B: 300Organization C: 180Organization D:
250Organization E: 150The goal is to produce a visually appealing bar
chart that effectively communicates the data. Ensure the chart includes
appropriate labels, title, and any necessary artistic elements to enhance its
visual appeal.
【Data Generation Code Example】

# Create input data

organizations = ['Organization A', 'Organization B', 'Organization C',


'Organization D', 'Organization E']

trees_planted = [120, 300, 180, 250, 150]


【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


# Create input data
organizations = ['Organization A', 'Organization B', 'Organization C',
'Organization D', 'Organization E'] # List of organizations
trees_planted = [120, 300, 180, 250, 150] # Number of trees planted by
each organization
# Create the bar chart
plt.figure(figsize=(10, 6)) # Set the figure size
plt.bar(organizations, trees_planted, color=['#66c2a5', '#fc8d62',
'#8da0cb', '#e78ac3', '#a6d854']) # Create bars with specific colors
# Add titles and labels
plt.title('Number of Trees Planted by Organizations in One Year') # Title
of the chart
plt.xlabel('Organizations') # X-axis label
plt.ylabel('Number of Trees Planted') # Y-axis label
# Add artistic elements
for i in range(len(organizations)):
plt.text(i, trees_planted[i] + 5, str(trees_planted[i]), ha='center',
va='bottom', fontsize=12, color='black') # Add text labels above the bars
# Display the chart
plt.show() # Show the chart

This problem requires the creation of a visually appealing bar chart to


compare the number of trees planted by different organizations over a year.
First, we import the necessary library, matplotlib.pyplot, to generate the
chart.
Next, we create the input data lists organizations and trees_planted,
representing the names of the organizations and the number of trees they
planted, respectively.
To create the bar chart, we use the plt.bar() function. The color parameter is
used to assign different colors to each bar, enhancing the visual appeal of
the chart. The plt.figure() function is used to set the size of the figure.
We then add the chart title and axis labels using plt.title(), plt.xlabel(), and
plt.ylabel(). These labels make the chart informative and easy to
understand.
To further enhance the chart, we add text labels above each bar using a for
loop and the plt.text() function. These labels display the exact number of
trees planted, making the data more accessible.
Finally, we use plt.show() to display the chart. This command renders the
chart, allowing us to see the final result.
This exercise helps users practice creating and customizing bar charts in
Python while focusing on the artistic aspects of data visualization. It
emphasizes the importance of clear labels, appropriate use of color, and
additional text annotations to make the chart more informative and visually
appealing.
【Trivia】
‣ Matplotlib, the library used in this exercise, is one of the most popular
plotting libraries in Python. It was created by John D. Hunter in 2003.
‣ The library allows the generation of plots and charts that can be easily
customized to suit various needs, making it a versatile tool for data
visualization.
‣ Effective data visualization is crucial in communicating insights clearly
and effectively. It's not just about presenting data but also about making it
understandable and engaging for the audience.
86. Scatter Plot Visual Art with Python
Importance★★★★☆
Difficulty★★★☆☆
A client from an art gallery wants to create a visually appealing scatter plot
to showcase on their website.
The scatter plot should contain 1400 points, each with different colors and
sizes.
Your task is to generate this scatter plot using Python, focusing on creating
a visually stunning piece of visual art.
Ensure that the plot is not only functional but also aesthetically pleasing.
Use the following code to generate the input data.

【Data Generation Code Example】

import numpy as np
np.random.seed(0)
x = np.random.rand(1400)
y = np.random.rand(1400)
colors = np.random.rand(1400)
area = (30 * np.random.rand(1400))**2
【Diagram Answer】

【Code Answer】

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.rand(1400)
y = np.random.rand(1400)
colors = np.random.rand(1400)
area = (30 * np.random.rand(1400))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Beautiful Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

This exercise aims to teach you how to create visually appealing scatter
plots using Python.
The focus is on the artistic aspect, ensuring that the plot is not only
informative but also aesthetically pleasing.
First, we generate the input data using NumPy.
We create 1400 random points for both x and y coordinates.
Each point is assigned a random color and size, making the plot diverse and
visually interesting.
In the answer code, we use Matplotlib to create the scatter plot.
The plt.scatter function is used to plot the points, with parameters for sizes
(s) and colors (c).
The alpha parameter is set to 0.5 to add transparency, enhancing the visual
effect.
We also add a title and labels for the x and y axes to make the plot more
informative.
By following these steps, you can create a scatter plot that is both functional
and visually stunning.
【Trivia】
‣ Scatter plots are commonly used to observe relationships between
variables.
‣ The transparency (alpha) parameter can help in visualizing overlapping
points in dense areas.
‣ Matplotlib is a powerful library for creating a wide range of static,
animated, and interactive plots in Python.
‣ The aesthetic aspect of data visualization is crucial in fields like data
journalism and scientific communication.
87. Pie Chart of Metal Distribution in a Sample
Importance★★★☆☆
Difficulty★★☆☆☆
A manufacturing company wants to analyze the composition of different
metals in their product samples.
Using Python, create a pie chart that visually represents the distribution of
different types of metals in a given sample.
The sample contains the following metals with their respective proportions:
Iron (40%), Copper (25%), Nickel (15%), Zinc (10%), and Aluminium
(10%).
Your task is to write a Python code that generates a pie chart for this data.

【Data Generation Code Example】

## Create data for the metal distribution

metal_types = ['Iron', 'Copper', 'Nickel', 'Zinc', 'Aluminium']


proportions = [40, 25, 15, 10, 10]
【Diagram Answer】

【Code Answer】

import matplotlib.pyplot as plt


## Create data for the metal distribution
metal_types = ['Iron', 'Copper', 'Nickel', 'Zinc', 'Aluminium']
proportions = [40, 25, 15, 10, 10]
## Create a pie chart
plt.figure(figsize=(8, 8))
plt.pie(proportions, labels=metal_types, autopct='%1.1f%%',
startangle=140)
plt.title('Distribution of Different Types of Metals in a Sample')
plt.show()

This task involves generating a pie chart to visualize the distribution of


various metals in a sample.
To achieve this, the matplotlib library in Python is used, which is a
powerful tool for creating static, animated, and interactive visualizations in
Python.‣ First, the data is defined: a list of metal types and their respective
proportions in the sample.
‣ The plt.pie function is then used to create the pie chart. This function
requires the proportions of each slice, the labels for each slice, and an
autopct parameter to display the percentage value on each slice.
‣ The startangle parameter is used to start the pie chart at a specified angle,
which can help in achieving a more visually appealing layout.
‣ Finally, the plt.title function adds a title to the chart, and plt.show displays
the chart.By running the provided code, a pie chart will be generated
showing the distribution of different types of metals in the sample. The
chart will be aesthetically pleasing and informative, suitable for
presentations or reports in a professional setting.
【Trivia】
The pie chart was first used in the early 19th century by the Scottish
engineer William Playfair, who is also credited with inventing several other
types of graphs, including the bar chart and line chart. Pie charts are
particularly useful for showing the relative proportions of a whole, and they
are widely used in business, media, and various industries for quick and
clear communication of data. However, they are most effective when used
with a small number of categories, as too many slices can make the chart
difficult to read and interpret.
Chapter 4 Request for review evaluation

Thank you for reading this book in its entirety.


Your journey through the 100 exercises aimed at showcasing the artistic
side of Python visual art has hopefully been both enlightening and
inspiring.
Each exercise was crafted with the intention of making complex visual
concepts accessible and engaging, with detailed explanations accompanying
the results of each piece of code to ensure clarity and understanding.I have
put a lot of effort into making this book a valuable resource for those who
already have a foundational understanding of programming and are looking
to explore the intersection of coding and art.
However, your feedback is crucial to me.Please take a moment to share
your thoughts, even if it's just a quick rating.
Every review is carefully read, and your insights often shape future
projects.
Whether you found the exercises helpful, enjoyed the artistic challenges, or
encountered any difficulties, your feedback will be greatly appreciated.If
you have suggestions for future themes or topics you'd like to see covered,
I'm all ears.
My goal is to continue providing useful and engaging content, and your
voice plays a vital role in that mission.So, if you found value in this book, if
it sparked new ideas, or even if it fell short of your expectations, please let
me know.
Your input helps improve future editions and inspires new projects.Thank
you once again for your time and for allowing this book to be a part of your
learning journey.
I look forward to hearing from you and hope to meet you again in future
works.
Appendix: Execution Environment
In this eBook, we will use Google Colab to run Python code.
Google Colab is a free Python execution environment that runs in your
browser.
Below are the steps to use Google Colab to execute Python code.

Log in with a Google account


First, log in to your Google account. If you don't have an account yet,
you need to create a new one.
Access Google Colab
Open your web browser and go to the following URL:
http://colab.research.google.com
Create a new notebook
Once the Google Colab homepage appears, click the "New Notebook"
button. This will create a new Python notebook.
Enter Python code
Enter Python code in the cell of the notebook. For example, enter the
following simple code:
print("Hello, Google Colab!")
Run the code
To run the code, click the play button (▶️) on the left side of the code
cell or select the cell and press Shift+Enter.
Check the execution result
If the code runs successfully, the result will be displayed below the cell.
In the above example, "Hello, Google Colab!" will be displayed.
Save the notebook
To save the notebook, select "Save to Drive" from the "File" menu at the
top of the screen. The notebook will be saved to your Google Drive.
Install libraries
If you need any Python libraries, enter the following in a cell and run it:
!pip install library-name
For example, to install numpy, do the following:
!pip install numpy
Open an existing notebook
To open an existing notebook, select the notebook from Google Drive or
choose "Open Notebook" from the "File" menu in Colab.
These are the steps to run Python code on Google Colab. With this, you can
easily use a Python execution environment in the cloud.

You might also like