matplotlib 库中的 plot 来绘制 K线图
时间: 2023-07-12 18:39:15 浏览: 60
是的,您可以使用 matplotlib 库中的 plot 函数来绘制 K 线图。下面是一个示例代码:
```python
import matplotlib.pyplot as plt
# 数据准备
data = [[1, 2, 3, 4], [30, 35, 25, 40], [25, 30, 20, 35], [28, 32, 28, 30]]
# 创建画布
fig = plt.figure()
# 添加子图
ax = fig.add_subplot(1, 1, 1)
# 绘制K线图
x = range(4)
for i in x:
if data[i][0] > data[i][3]:
ax.plot([i, i], [data[i][1], data[i][0]], 'r', lw=2)
ax.plot([i, i], [data[i][3], data[i][2]], 'r', lw=2)
else:
ax.plot([i, i], [data[i][1], data[i][2]], 'g', lw=2)
ax.plot([i, i], [data[i][3], data[i][0]], 'g', lw=2)
# 设置x轴刻度
ax.set_xticks(x)
ax.set_xticklabels(['2019/1/1', '2019/1/2', '2019/1/3', '2019/1/4'])
# 设置y轴刻度范围
ymin, ymax = min([min(d) for d in data]), max([max(d) for d in data])
ax.set_ylim(ymin-1, ymax+1)
# 设置标题和坐标轴标签
ax.set_title('K线图')
ax.set_ylabel('股价')
ax.set_xlabel('日期')
# 显示图形
plt.show()
```
注意,该示例代码中的数据是一个 4x4 的矩阵,每一行表示一天的开盘价、收盘价、最低价和最高价。您可以根据您的实际数据进行修改。