Common Chart Generation Code Examples in Python
Introduction
This document organizes code examples for generating various common charts using Python, including bar charts, line charts, pie charts, and more. All code is implemented based on the Matplotlib and Seaborn libraries, ensuring simplicity and clarity for direct execution.
Environment Setup
First, you need to install the necessary libraries:
pip install matplotlib seaborn numpy pandas
1. Bar Chart
Bar charts are suitable for comparing data values across different categories.
1.1 Basic Vertical Bar Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
categories = ['A', 'B', 'C', 'D', 'E']
values = np.array([35, 25, 40, 30, 45])
# Create chart
plt.figure(figsize=(10, 6))
bars = plt.bar(categories, values, color='skyblue')
# Customize style
plt.title('Basic Vertical Bar Chart', fontsize=15)
plt.xlabel('Category', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Add data labels
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height}',
ha='center', va='bottom')
plt.show()
To display Chinese characters, add the following code
# Set Chinese font and resolve negative sign display issue
plt.rcParams['font.sans-serif'] = ['SimHei'] # To display Chinese labels correctly
plt.rcParams['axes.unicode_minus'] = False # To display negative signs correctly
1.2 Horizontal Bar Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
categories = ['A', 'B', 'C', 'D', 'E']
values = np.array([35, 25, 40, 30, 45])
# Create chart
plt.figure(figsize=(10, 6))
bars = plt.barh(categories, values, color='lightgreen')
# Customize style
plt.title('Horizontal Bar Chart', fontsize=15)
plt.xlabel('Value', fontsize=12)
plt.ylabel('Category', fontsize=12)
plt.grid(axis='x', linestyle='--', alpha=0.7)
# Add data labels
for bar in bars:
width = bar.get_width()
plt.text(width, bar.get_y() + bar.get_height()/2.,
f'{width}',
ha='left', va='center')
plt.show()
1.3 Grouped Bar Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
categories = ['A', 'B', 'C', 'D', 'E']
values1 = np.array([35, 25, 40, 30, 45])
values2 = np.array([25, 35, 30, 45, 35])
# Set bar width
bar_width = 0.35
index = np.arange(len(categories))
# Create chart
plt.figure(figsize=(12, 6))
bars1 = plt.bar(index, values1, bar_width, label='Group 1', color='skyblue')
bars2 = plt.bar(index + bar_width, values2, bar_width, label='Group 2', color='lightgreen')
# Customize style
plt.title('Grouped Bar Chart', fontsize=15)
plt.xlabel('Category', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.xticks(index + bar_width/2, categories)
plt.legend()
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
2. Line Chart
Line charts are suitable for showing trends in data over time or ordered categories.
2.1 Basic Line Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create chart
plt.figure(figsize=(12, 6))
plt.plot(x, y, color='blue', linewidth=2, linestyle='-')
# Customize style
plt.title('Basic Line Chart', fontsize=15)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.grid(linestyle='--', alpha=0.7)
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.show()
2.2 Multiple Line Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) + np.cos(x)
# Create chart
plt.figure(figsize=(12, 6))
plt.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, y2, label='cos(x)', color='red', linewidth=2, linestyle='--')
plt.plot(x, y3, label='sin(x)+cos(x)', color='green', linewidth=2, linestyle='-.')
# Customize style
plt.title('Multiple Line Chart', fontsize=15)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.legend(fontsize=10)
plt.grid(linestyle='--', alpha=0.7)
plt.show()
2.3 Line Chart with Markers
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
x = np.arange(1, 11)
y = np.array([12, 15, 13, 17, 19, 21, 18, 23, 25, 22])
# Create chart
plt.figure(figsize=(12, 6))
plt.plot(x, y, color='purple', linewidth=2, marker='o', markersize=8, markerfacecolor='white', markeredgewidth=2)
# Customize style
plt.title('Line Chart with Markers', fontsize=15)
plt.xlabel('Time', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.grid(linestyle='--', alpha=0.7)
# Add data labels
for i, j in zip(x, y):
plt.text(i, j+0.5, f'{j}', ha='center', va='bottom', fontsize=10)
plt.show()
3. Pie Chart
Pie charts are suitable for showing the proportion of each part to the whole.
3.1 Basic Pie Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
# Create chart
plt.figure(figsize=(8, 8))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
# Ensure pie chart is a circle
plt.axis('equal')
plt.title('Basic Pie Chart', fontsize=15)
plt.show()
3.2 Donut Chart
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
explode = (0.1, 0, 0, 0) # Highlight the first part
# Create chart
plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90, wedgeprops={'width': 0.3})
# Ensure pie chart is a circle
plt.axis('equal')
plt.title('Donut Chart', fontsize=15)
plt.show()
4. Other Common Charts
4.1 Scatter Plot
import matplotlib.pyplot as plt
import numpy as np
# Data preparation
np.random.seed(42)
x = np.random.randn(100)
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
# Create chart
plt.figure(figsize=(10, 10))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
# Add color bar
plt.colorbar(scatter, label='Color Value')
plt.title('Scatter Plot', fontsize=15)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.grid(linestyle='--', alpha=0.7)
plt.show()
4.2 Histogram
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Set Seaborn style
sns.set_style("whitegrid")
# Data preparation
np.random.seed(42)
data = np.random.randn(1000)
# Create chart
plt.figure(figsize=(12, 6))
sns.histplot(data, bins=30, kde=True, color='teal', edgecolor='black')
plt.title('Histogram (with Density Curve)', fontsize=15)
plt.xlabel('Value', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.show()
4.3 Box Plot
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Set Seaborn style
sns.set_style("whitegrid")
# Data preparation
np.random.seed(42)
data = [np.random.normal(0, std, 100) for std in range(1, 5)]
labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4']
# Create chart
plt.figure(figsize=(12, 6))
sns.boxplot(data=data, palette='Set2')
plt.xticks(range(len(labels)), labels)
plt.title('Box Plot', fontsize=15)
plt.xlabel('Group', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.show()
Conclusion
This document provides code examples for generating commonly used charts in Python, covering basic types such as bar charts, line charts, and pie charts, as well as extended types like scatter plots, histograms, and box plots. Each example includes data preparation, chart drawing, and style customization sections, allowing users to modify and expand based on their actual needs.
To save the chart, you can add the following code before plt.show():
# Save as PNG image
plt.savefig('chart_name.png', dpi=300, bbox_inches='tight')
# Save as PDF file
plt.savefig('chart_name.pdf', bbox_inches='tight')
It is recommended to refer to the official documentation of Matplotlib and Seaborn to explore more advanced customization options and chart types.