答案 0 :(得分:1)
ax.axhline
在给定高度绘制一条水平线,默认跨越绘图的整个宽度。
ax.text
在给定位置放置文本。使用 y 轴变换,可以将 x 坐标指定为相对于轴的位置,将 y 坐标指定为数据值。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
y_name = 'Port ME Homemade Mass Flow Rate (kg/s)'
df1before = pd.DataFrame({'Speed': np.random.uniform(.1, 1, 100) ** 3 * 4,
y_name: np.random.normal(.053, .01, 100)})
df1after = pd.DataFrame({'Speed': np.random.uniform(.1, 1, 100) ** 3 * 4,
y_name: np.random.normal(.057, .01, 100)})
fig, ax = plt.subplots(figsize=(20, 10), dpi=100)
ax.scatter(x='Speed', y=y_name, data=df1before, color='r', marker='1', label='Before')
ax.scatter(x='Speed', y=y_name, data=df1after, color='b', marker='x', label='After')
ax.set_xlabel('Speed(Knot)')
ax.set_ylabel('Port ME Homemade Mass Flow Rate (kg/s)')
mean_before = df1before[y_name].mean()
ax.axhline(df1before[y_name].mean(), color='r', ls='--')
ax.text(1, mean_before, f'mean: {mean_before:.4f}\n',
ha='right', va='center', color='r', transform=ax.get_yaxis_transform())
mean_after = df1after[y_name].mean()
ax.axhline(df1after[y_name].mean(), color='b', ls='--')
ax.text(1, mean_after, f'mean: {mean_after:.4f}\n',
ha='right', va='center', color='b', transform=ax.get_yaxis_transform())
ax.legend()
plt.tight_layout()
plt.show()