Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add black border to matplotlib 2.0 'ax' object In Python 3?
To add a black border to a matplotlib 2.0 'ax' object in Python, you can configure the axes properties to make the plot borders more prominent. This is useful for creating cleaner, more professional-looking visualizations.
Using rcParams to Set Global Axes Properties
The most efficient approach is to use plt.rcParams to set the axes edge color and line width globally ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Set black border properties
plt.rcParams["axes.edgecolor"] = "black"
plt.rcParams["axes.linewidth"] = 2.50
# Create sample data
N = 10
x = np.random.randint(low=0, high=N, size=N)
y = np.random.randint(low=0, high=N, size=N)
# Plot the data
plt.plot(x, y, color='red', marker='o')
plt.title('Plot with Black Border')
plt.show()
Setting Border Properties for Specific Axes
You can also set border properties for individual axes objects using the spines attribute ?
import matplotlib.pyplot as plt
import numpy as np
# Create figure and axes
fig, ax = plt.subplots(figsize=(7, 4))
# Set black border for all spines
for spine in ax.spines.values():
spine.set_edgecolor('black')
spine.set_linewidth(2.5)
# Create sample data
x = np.linspace(0, 10, 20)
y = np.sin(x)
# Plot the data
ax.plot(x, y, color='blue', linewidth=2)
ax.set_title('Sine Wave with Custom Black Border')
ax.grid(True, alpha=0.3)
plt.show()
Comparison of Methods
| Method | Scope | Best For |
|---|---|---|
plt.rcParams |
Global (all plots) | Consistent styling across multiple plots |
ax.spines |
Individual axes | Customizing specific plots |
Customizing Individual Spine Properties
For more control, you can customize each border individually ?
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(6, 4))
# Customize individual spines
ax.spines['top'].set_color('black')
ax.spines['top'].set_linewidth(3)
ax.spines['bottom'].set_color('black')
ax.spines['bottom'].set_linewidth(3)
ax.spines['left'].set_color('black')
ax.spines['left'].set_linewidth(3)
ax.spines['right'].set_color('black')
ax.spines['right'].set_linewidth(3)
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
ax.bar(x, y, color='green', alpha=0.7)
ax.set_title('Bar Chart with Thick Black Border')
plt.show()
Conclusion
Use plt.rcParams to set black borders globally for consistent styling. For individual plot customization, use the ax.spines attribute to control border color and thickness precisely.
Advertisements
