figure方法
figure方法可以设置绘图对象的长、宽、分辨率及背景颜色等。
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data/iris.csv')
plt.figure(figsize=(12, 3), dpi=120, facecolor='red')
x = data['sepal_length']
plt.plot(x)
plt.show()
一个平面多个图像
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
y_tan = np.tan(x)
# 一行三列,第一幅图
plt.subplot(1, 3, 1)
plt.plot(x, y_sin, 'ob')
plt.title('sin')
# 一行三列,第二幅图
plt.subplot(1,3,2)
plt.plot(x, y_cos, '*m')
plt.title('cos')
# 一行三列,第三幅图
plt.subplot(133)
plt.plot(x, y_tan, ':r')
plt.title('tan')
plt.show()
详情见:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html
设置字体、显示中文、add_axes增加子区域
import matplotlib.pyplot as plt
import pandas as pd
df1 = pd.read_csv('data\iris.csv')
plt.rc('font', family='SimHei', size=13)
# 第一块区域
fig = plt.figure()
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(df1['sepal_length'], 'r')
ax1.set_title('area区域')
# 第二块区域
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(df1['sepal_width'], 'b')
ax2.set_title('area子区域')
plt.show()
图题
import matplotlib.pyplot as plt
import pandas as pd
df1 = pd.read_csv('data\iris.csv')
plt.rc('font', family='SimHei', size=13)
fig, ax = plt.subplots()
ax.plot(df1['sepal_length'], label = 'sepal_length')
ax.legend(loc=2) # 左上角
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_title('定制标题')
plt.show()
grid方法设置网格线
import matplotlib.pyplot as plt
import pandas as pd
df1 = pd.read_csv('data\iris.csv')
plt.rc('font', family='SimHei', size=13)
fig, ax = plt.subplots()
ax.plot(df1['sepal_length'], label = 'sepal_length')
# 设置网格:蓝色、透明度、样式、宽度
ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)
ax.legend(loc=4) # 右下角
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_title('网格线外观')
plt.show()