Python (2024)
Python (2024)
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.
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()
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()
【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)
【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()
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()
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()
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()
【Code Answer】
【Code Answer】
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】
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.
market_shares=[30,25,20,25]
【Diagram Answer】
【Code Answer】
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.
import random
ages = [random.randint(1, 100) for _ in range(100)]
【Diagram Answer】
【Code Answer】
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()
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()
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()
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()
【Code Answer】
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】
【Code Answer】
import numpy as np
np.random.seed(0)
x = np.random.rand(200)
y = np.random.rand(200)
colors = np.random.rand(200)
【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()
【Code Answer】
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.
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 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.
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()
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()
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()
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()
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.
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()
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()
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()
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()
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()
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()
【Code Answer】
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
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
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()
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
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.
【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
【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】
【Code Answer】
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()
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()
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
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()
【Code Answer】
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()
【Code Answer】
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()
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()
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()
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()
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()
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()
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()
【Code Answer】
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()
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()
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()
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()
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()
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 numpy as np
data = {
'x': np.random.rand(800),
'y': np.random.rand(800),
'colors': np.random.rand(800)
}
【Diagram Answer】
【Code Answer】
【Code Answer】
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()
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()
import numpy as np
data = np.random.rand(12, 12)
【Diagram Answer】
【Code Answer】
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()
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】
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()
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()
insect_data={'Butterflies':35,'Bees':25,'Beetles':20,'Dragonflies':10,'Other
insects':10}
【Diagram Answer】
【Code Answer】
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:
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】
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.
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()
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()
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
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()
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.
【Code Answer】
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()
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()
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()
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
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 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
# 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
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.
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.
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.
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()#プロットを表示
【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)
【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.
【Code Answer】
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.
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()
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()
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()
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()
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()
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()
【Code Answer】
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()
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()
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()
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()
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()
import networkx as nx
import random
G = nx.gnm_random_graph(60, 65)
【Diagram Answer】
【Code Answer】
【Code Answer】
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.
【Code Answer】