看了许多书本中的画图示例,有直接在plt上画的,也有用ax画的,这两者究竟是什么,又有哪些区别呢。
从下面这一行代码进行解读:
fig,ax=plt.subplots()
在任何绘图之前,我们需要一个Figure对象,至少要有这一层才可以画。.plt 对应的就是最高层 scripting layer。这就是为什么它简单上手,但要调细节就不灵了。即:
fig=plt.figure()
ax.plot 是在 artist layer 上操作。基本上可以实现任何细节的调试。
代码如下(示例):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
代码如下(示例):
数据集格式
# Create figure
plt.figure(figsize=(12,6),dpi=300)
# Create bar plot
labels = data['MovieTitle']
t = data['Tomatometer']
a = data['AudienceScore']
x=np.arange(0,len(labels)*2,2)
width = 0.6
plt.bar(x-width/2,t,width=width,label='Tomatometer')
plt.bar(x+width/2,a,width=width,label='AudienceScore')
# Specify ticks
# Get current Axes for setting tick labels and horizontal grid
# Set tick labels
plt.xticks(x,labels=labels,rotation=20)
# Add minor ticks for y-axis in the interval of 5
plt.minorticks_on()
y = []
for i in range(0,101,20):
if i % 20 ==0:
y.append(str(i)+'%')
y1 = np.arange(0,101,20)
plt.yticks(y1,y)
# Add major horizontal grid with solid lines
plt.grid(which='major', axis='y',ls='-')
# Add minor horizontal grid with dashed lines
plt.grid(which='minor', axis='y',ls=':')
# Add title
plt.title('Movie comparison')
# Add legend
plt.legend()
# Show plot
plt.show()
from matplotlib.ticker import MultipleLocator
# Create figure
plt.figure(figsize=(16,8),dpi=300)
# Create bar plot
labels = data['MovieTitle']
t = data['Tomatometer']
a = data['AudienceScore']
x=np.arange(0,len(labels)*2,2)
width = 0.4
ax=plt.gca()
ax.bar(x-width/2,t,width=width,label='Tomatometer')
ax.bar(x+width/2,a,width=width,label='AudienceScore')
# Specify ticks
plt.xticks(x,labels=labels,rotation=20)
# Get current Axes for setting tick labels and horizontal grid
# Set tick labels
yticks = ["0%","20%","40%","60%","80%","100%"]
y_ = np.arange(0,101,20)
ax.set_yticks(y_)
ax.set_yticklabels(yticks,fontsize=10) #
# Add minor ticks for y-axis in the interval of 5
yminorLocator = MultipleLocator(5)
ax.yaxis.set_minor_locator(yminorLocator)
# Add major horizontal grid with solid lines
ax.grid(which='major',linestyle='-',axis='y')
# Add minor horizontal grid with dashed lines
ax.grid(which="minor",linestyle=':')
# Add title
ax.set_title("Compare with Tomatometer & Audidence Score",fontsize=15)
# Add legend
ax.legend()
# Show plot
plt.show()
如果将Matplotlib绘图和我们平常画画相类比,可以把Figure想象成一张纸(一般被称之为画布),Axes代表的则是纸中的一片区域(当然可以有多个区域,这是后续要说到的subplots),上一张更形象一点的图。