Creating Common Charts with Matplotlib in Python: Line, Histogram, Bar, and Pie
This tutorial explains how to use Python's Matplotlib library to generate common visualizations such as line, histogram, bar, and pie charts, covering the basic workflow, code examples, and function signatures for quick data analysis and reporting.
In daily work, developers often need to analyze project data and produce visual reports; this article introduces how to use the Matplotlib library to create common 2D charts in Python, including line, histogram, bar, and pie charts.
Matplotlib is a widely used Python visualization tool; its core module pyplot allows developers to generate charts with just a few lines of code.
The basic plotting workflow consists of creating a canvas, optionally creating subplots, adding titles and axis labels, setting axis limits and ticks, drawing the graphics, displaying the figure, and finally saving it.
Line chart example :
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
x = np.arange(0,10,1) # horizontal data
y = x**2 # vertical data
plt.figure(figsize=(6,4), dpi=90)
plt.title('折线图')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.xlim(0,10)
plt.ylim(0,105)
plt.xticks([0,2,4,6,8,10])
plt.yticks([0,25,50,75,100])
plt.plot(x, y, label='平方')
plt.legend()
plt.grid(True)
plt.show()The matplotlib.pyplot.plot function signature is:
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)Other common chart types are demonstrated with their function prototypes:
Histogram :
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)Bar chart :
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)Pie chart :
matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0,0), frame=False, rotatelabels=False, *, normalize=True, data=None)By following these examples, developers can quickly produce attractive visualizations, allowing them to focus on data acquisition, processing, analysis, and storage rather than the intricacies of chart rendering.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
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.