以往都是使用plt ,但是在多子图绘制时总是需要ax ,所以这篇博客使用一个案例来练习ax 绘图
matplotlib使用plt 绘图可以参考:Matplotlib 整合与细节操作(样式、图例、风格、轴线、网格)
使用ax 绘图时,有时需要魔改一些内容,就与plt的api不一样:
ax.title.set_text("我是标题")
ax.yaxis.set_ticks_position('right')
ax.yaxis.set_label_position("right")
ax.set_ylabel("y值")
ax.set_xlabel("x值")
ax.set_ylim(-10, 20)
代码示例
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import numpy as np
mpl.rcParams['font.family'] = ['Heiti TC']
def draw_form_df(dataframe: pd.DataFrame, title_name: str) -> plt.Figure:
"""绘制dataframe的正式的图"""
fig = plt.figure(figsize=(10, 5))
grid = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(grid[0, 0])
for index, line_value in dataframe.iterrows():
ax.plot(list(range(dataframe.shape[1])), line_value.values, label=index)
ax.axhline(y=0, ls=":", c="red")
ax.set_ylim(-10, 20)
ax.title.set_text(title_name)
ax.yaxis.set_ticks_position('right')
ax.yaxis.set_label_position("right")
ax.set_ylabel("y值")
ax.set_xlabel("x值")
ax.legend()
return fig
if __name__ == '__main__':
df = pd.DataFrame(
data=[np.random.normal(0, 1, 200),
np.random.normal(5, 3, 200),
np.random.normal(2, 2, 200)], index=['line1', 'line2', 'line3'])
fig = draw_form_df(df, "标题")
fig.show()
效果图:
|