# Create a simple line plotplt.plot([1,2,3,4],[1,4,9,16])plt.xlabel('x label')plt.ylabel('y label')plt.title('Simple Plot')plt.show()
Plot Types
Line Plot
# Line plot with customizationplt.plot(x,y,label='Line 1',color='b',linestyle='-',marker='o')plt.xlabel('x label')plt.ylabel('y label')plt.title('Line Plot')plt.legend()plt.show()
Scatter Plot
# Scatter plot with customizationplt.scatter(x,y,label='Data points',color='r',marker='x')plt.xlabel('x label')plt.ylabel('y label')plt.title('Scatter Plot')plt.legend()plt.show()
Bar Plot
# Bar plot with customizationplt.bar(x,height,label='Bars',color='g')plt.xlabel('x label')plt.ylabel('Height')plt.title('Bar Plot')plt.legend()plt.show()
Histogram
# Histogram with customizationplt.hist(data,bins=10,label='Data',color='m',edgecolor='black')plt.xlabel('Value')plt.ylabel('Frequency')plt.title('Histogram')plt.legend()plt.show()
Pie Chart
# Pie chart with customizationplt.pie(sizes,labels=labels,autopct='%1.1f%%',startangle=140)plt.axis('equal')# Equal aspect ratio ensures that pie is drawn as a circle.plt.title('Pie Chart')plt.show()
Box Plot
# Box plot with customizationplt.boxplot(data)plt.title('Box Plot')plt.show()
# Multiple subplots in one figurefig,axs=plt.subplots(2,2)axs[0,0].plot(x,y)axs[0,0].set_title('Subplot 1')axs[0,1].scatter(x,y)axs[0,1].set_title('Subplot 2')axs[1,0].bar(x,height)axs[1,0].set_title('Subplot 3')axs[1,1].hist(data)axs[1,1].set_title('Subplot 4')plt.tight_layout()plt.show()
Customizing the Figure Size
plt.figure(figsize=(10,5))plt.plot(x,y)plt.show()
Example
Complete Example
importmatplotlib.pyplotasplt# Sample datax=[1,2,3,4,5]y=[2,3,5,7,11]# Create a figure and a set of subplotsfig,axs=plt.subplots(2,2,figsize=(10,10))# Line plotaxs[0,0].plot(x,y,label='Line 1',color='b',linestyle='-',marker='o')axs[0,0].set_title('Line Plot')axs[0,0].legend()# Scatter plotaxs[0,1].scatter(x,y,label='Data points',color='r',marker='x')axs[0,1].set_title('Scatter Plot')axs[0,1].legend()# Bar plotaxs[1,0].bar(x,y,label='Bars',color='g')axs[1,0].set_title('Bar Plot')axs[1,0].legend()# Histogramdata=[1,2,2,3,3,3,4,4,4,4]axs[1,1].hist(data,bins=4,label='Data',color='m',edgecolor='black')axs[1,1].set_title('Histogram')axs[1,1].legend()# Show the plotsplt.tight_layout()plt.show()