Comprehensive Matplotlib Tutorial: Titles, Text, Annotations, Labels, Legends, Colors, Markers, Grids, Axes, Styles and More
This article provides a step‑by‑step guide to using Matplotlib for creating and customizing plots in Python, covering how to add titles, text, annotations, axis labels, legends, colors, markers, grids, axis limits, dual axes, filled areas, patches, and style themes, complete with runnable code examples and visual results.
This tutorial demonstrates a wide range of Matplotlib features for creating and customizing plots in Python.
1. Adding a title
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(0, 10)
plt.title('这是一个示例标题')
plt.plot(x, x*x)
plt.show()2. Adding text – Use plt.text(x, y, 'your text') to place arbitrary text at a specific coordinate.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(-10, 11, 1)
y = x*x
plt.plot(x, y)
plt.title('这是一个示例标题')
plt.text(-2.5, 30, 'function y=x*x')
plt.show()3. Adding annotations – The annotate() function adds labeled arrows.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(-10, 11, 1)
y = x*x
plt.plot(x, y)
plt.title('这是一个示例标题')
plt.annotate('这是一个示例注释', xy=(0,1), xytext=(-2,22), arrowprops={'headwidth':10,'facecolor':'r'})
plt.show()4. Setting axis labels – Use plt.xlabel() and plt.ylabel() to name the axes.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(1, 20)
plt.xlabel('示例x轴')
plt.ylabel('示例y轴')
plt.plot(x, x*x)
plt.show()5. Adding a legend – Call plt.legend() with a list of labels to differentiate multiple lines.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 20)
plt.plot(x, x)
plt.plot(x, x*2)
plt.plot(x, x*3)
plt.plot(x, x*4)
plt.legend(['生活','颜值','工作','金钱'])
plt.show()6. Adjusting colors – The color argument of plot() accepts named colors, hex codes, grayscale values, or RGB tuples.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,5)
plt.plot(x, color='g')
plt.plot(x+1, color='0.5')
plt.plot(x+2, color='#FF00FF')
plt.plot(x+3, color=(0.1,0.2,0.3))
plt.show()7. Changing line markers – Use the marker parameter to select symbols such as 'o', '>', 's', etc.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,5)
plt.plot(x, marker='o')
plt.plot(x+1, marker='>')
plt.plot(x+2, marker='s')
plt.show()8. Displaying mathematical formulas – Enclose LaTeX‑style expressions in $...$ and use r'...' strings.
import numpy as np
import matplotlib.pyplot as plt
plt.title('chenqionghe')
plt.xlim([1,8])
plt.ylim([1,5])
plt.text(2,4, r'$ \alpha \beta \pi \lambda \omega $', size=25)
plt.text(4,4, r'$ \sin(0)=\cos(\frac{\pi}{2}) $', size=25)
plt.text(2,2, r'$ \lim_{x \rightarrow y} \frac{1}{x^3} $', size=25)
plt.text(4,2, r'$ \sqrt[4]{x}=\sqrt{y} $', size=25)
plt.show()9. Adding a grid – Call plt.grid() (optional arguments for color, linewidth, linestyle).
import numpy as np
import matplotlib.pyplot as plt
x = ['a','b','c','d']
y = [15,30,45,10]
plt.grid()
plt.plot(x, y)
plt.show()10. Adjusting tick density – Use plt.locator_params(nbins=20) to set the number of ticks on both axes, or specify 'x' or 'y' for a single axis.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,30,1)
plt.plot(x, x)
plt.locator_params(nbins=20)
plt.show()11. Setting axis limits – plt.axis([xmin, xmax, ymin, ymax]), plt.xlim(), and plt.ylim() control view ranges.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,30,1)
plt.plot(x, x*x)
plt.xlim(xmin=10, xmax=25)
plt.show()12. Auto‑formatting date labels – After plotting dates, call plt.gcf().autofmt_xdate() to rotate them.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = pd.date_range('2020/01/01', periods=30)
y = np.arange(0,30)
plt.plot(x, y)
plt.gcf().autofmt_xdate()
plt.show()13. Adding a secondary y‑axis – plt.twinx() creates a twin axis for overlaying another dataset.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,20)
y1 = x*x
y2 = np.log(x)
plt.plot(x, y1)
plt.twinx()
plt.plot(x, y2, 'r')
plt.show()14. Filling areas – plt.fill() fills under a curve; plt.fill_between() fills between two curves.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,5*np.pi,1000)
y1 = np.sin(x)
y2 = np.sin(2*x)
plt.plot(x, y1)
plt.plot(x, y2)
plt.fill(x, y1, 'g')
plt.fill(x, y2, 'r')
plt.title('这是一个示例标题')
plt.show()
plt.fill_between(x, y1, y2, where=y1>y2, interpolate=True)
plt.show()15. Drawing patches – Use matplotlib.patches to add circles, rectangles, polygons, ellipses, etc.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mptaches
xy1 = np.array([0.2,0.2])
xy2 = np.array([0.2,0.8])
xy3 = np.array([0.8,0.2])
xy4 = np.array([0.8,0.8])
fig, ax = plt.subplots()
circle = mptaches.Circle(xy1, 0.15)
ax.add_patch(circle)
rect = mptaches.Rectangle(xy2, 0.2, 0.1, color='r')
ax.add_patch(rect)
polygon = mptaches.RegularPolygon(xy3, 6, 0.1, color='g')
ax.add_patch(polygon)
ellipse = mptaches.Ellipse(xy4, 0.4, 0.2, color='c')
ax.add_patch(ellipse)
ax.axis('equal')
plt.show()16. Changing plot style – Use plt.style.use('ggplot') (or any available style) to alter the overall appearance.
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, axes = plt.subplots(2,2)
ax1, ax2, ax3, ax4 = axes.ravel()
# Example subplots omitted for brevity
plt.show()The article concludes with a disclaimer that the content is compiled from the internet and retains the original author's copyright.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
