Matplotlib Python
Matplotlib Python
Today
Comprehensive Matplotlib Python Program Guide
Comprehensive Python Program Using SymPy
Comprehensive NumPy Matrix Operations Tutorial
Python Program for Matrix Operations and Decompositions
Yesterday
Translate Chinese Math Questions to PDF
7 Days
Impact of Inflation on Textile Workers' Well-being
30 Days
LaTeX Document for Calculus Quiz PDF
Exploring the Complexity of the Collatz Conjecture
Medium-difficulty number theory questions for math competitions
2025-06
Proving Non-Prime Nature of Expression
Simple Fun Mathematical Games for Kids
2025-05
True/False Questions on Trapezoidal and Simpson's Rules
Matrix Norms Exam Questions with Python
Exam Questions on Markov Chains with Python
Python Program for 1D Random Walk Plotting
3-State Markov Chain Transition Matrix Example
Proof of Uniform Distribution Transformation
Python Numerical Computing Assignment Guide
Python Program to Plot Feasible Region
Fixing Linear Regression Code Errors
2025-04
Simple Python Machine Learning Program Example
write a python program to simula
Find PDF from given CDF F(x)
Python Program to Plot Normal CDF
Uniform Continuity of Square Root Function
Python Program to Calculate Matrix Norms
Python Implementation of Dolittle Method
Best Python Books for Simulation Techniques
Function Continuous at Two Specific Points
Function Continuous Only at One Point
Get App
Comprehensive Matplotlib Python Program Guide
give a python program which completely covers all aspect of matplotlib
# =====================
# 1. Basic Configuration
# =====================
plt.rcParams.update({
'font.size': 10,
'figure.figsize': (12, 8),
'figure.dpi': 100,
'figure.autolayout': True
})
# ===============
# 2. Create Data
# ===============
x = np.linspace(0, 10, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)
y_random = np.random.normal(size=100)
categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 45]
date_strings = ['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01']
dates = [datetime.strptime(d, '%Y-%m-%d') for d in date_strings]
# ============================
# 3. Multiple Plot Arrangement
# ============================
fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(3, 3)
# ===============
# 4. Line Plot
# ===============
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(x, y_sin, 'b-', label='Sine', linewidth=2)
ax1.plot(x, y_cos, 'r--', label='Cosine', alpha=0.7)
ax1.set_title('Trigonometric Functions')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
ax1.legend()
ax1.grid(True, linestyle='--', alpha=0.6)
ax1.set_xlim(0, 10)
ax1.set_ylim(-1.5, 1.5)
# ===============
# 5. Scatter Plot
# ===============
ax2 = fig.add_subplot(gs[0, 1])
colors = np.random.rand(100)
sizes = 100 * np.random.rand(100)
ax2.scatter(x, y_random, c=colors, s=sizes, alpha=0.7,
cmap='viridis', edgecolor='black')
ax2.set_title('Scatter Plot')
ax2.set_xlabel('X values')
ax2.set_ylabel('Random values')
# =============
# 6. Bar Chart
# =============
ax3 = fig.add_subplot(gs[0, 2])
x_indexes = np.arange(len(categories))
bar_width = 0.6
ax3.bar(x_indexes, values, width=bar_width, color='skyblue',
edgecolor='black')
ax3.set_title('Bar Chart')
ax3.set_xticks(x_indexes)
ax3.set_xticklabels(categories)
ax3.set_ylabel('Values')
# ================
# 7. Histogram
# ================
ax4 = fig.add_subplot(gs[1, 0])
mu, sigma = 100, 15
data = np.random.normal(mu, sigma, 1000)
ax4.hist(data, bins=30, density=True, alpha=0.7,
color='green', histtype='stepfilled', edgecolor='black')
ax4.set_title('Histogram with PDF')
ax4.set_xlabel('Values')
ax4.set_ylabel('Frequency')
# Overlay PDF
xmin, xmax = plt.xlim()
x_pdf = np.linspace(xmin, xmax, 100)
p = (1/(sigma * np.sqrt(2 * np.pi))) * np.exp(-(x_pdf - mu)**2 / (2 *
sigma**2))
ax4.plot(x_pdf, p, 'r--', linewidth=2)
# ===============
# 8. Pie Chart
# ===============
ax5 = fig.add_subplot(gs[1, 1])
explode = (0.1, 0, 0, 0)
ax5.pie(values, explode=explode, labels=categories, autopct='%1.1f%%',
shadow=True, startangle=90,
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99'])
ax5.set_title('Pie Chart')
# ===================
# 9. Box and Whisker
# ===================
ax6 = fig.add_subplot(gs[1, 2])
data_to_plot = [np.random.normal(0, std, 100) for std in range(1, 4)]
ax6.boxplot(data_to_plot, patch_artist=True,
boxprops=dict(facecolor='lightblue'),
flierprops=dict(marker='o', markersize=5),
medianprops=dict(color='red'))
ax6.set_title('Box Plot')
ax6.set_xticklabels(['Group 1', 'Group 2', 'Group 3'])
# ==============
# 10. Error Bars
# ==============
ax7 = fig.add_subplot(gs[2, 0])
x_error = np.arange(5)
y_error = [2, 3, 5, 4, 6]
y_err = [0.5, 0.4, 0.9, 0.3, 0.7]
ax7.errorbar(x_error, y_error, yerr=y_err, fmt='o',
capsize=5, ecolor='red', elinewidth=2)
ax7.set_title('Error Bars')
ax7.set_xticks(x_error)
ax7.set_xticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May'])
# ==============
# 11. Date Plot
# ==============
ax8 = fig.add_subplot(gs[2, 1])
ax8.plot(dates, values, 'o-')
ax8.set_title('Date Handling')
ax8.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
ax8.xaxis.set_major_locator(mdates.MonthLocator())
ax8.grid(True)
fig.autofmt_xdate(rotation=45)
# =============
# 12. 3D Plot
# =============
ax9 = fig.add_subplot(gs[2, 2], projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax9.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=True)
ax9.set_title('3D Surface Plot')
fig.colorbar(surf, ax=ax9, shrink=0.5)
# =====================
# 13. Annotations/Text
# =====================
ax1.annotate('Max Sine', xy=(np.pi/2, 1), xytext=(4, 1.2),
arrowprops=dict(facecolor='black', shrink=0.05))
ax3.text(0, 42, 'Important Value', fontsize=9,
bbox=dict(facecolor='yellow', alpha=0.5))
# =====================
# 14. Saving the Figure
# =====================
plt.savefig('matplotlib_comprehensive_guide.png', dpi=300,
bbox_inches='tight')
bash
New chat