如何在Python中添加成交量柱状图?含Bittrex加密货币K线图方案
给Python K线图添加成交量柱状图的解决方案
嘿,我知道你已经搞定了Bittrex加密货币的K线图,现在想补上成交量展示对吧?这其实不难,咱们直接修改你的代码就能实现,核心是用matplotlib的子图功能把K线图和成交量图上下布局,再给成交量柱子加上涨跌配色更直观。
第一步:补全数据整理逻辑
首先你需要把K线的OHLC数据和成交量数据分别整理成列表,方便后续绘图:
import urllib2 import json from matplotlib.finance import candlestick2_ohlc import matplotlib.pyplot as plt import matplotlib.ticker as ticker # 假设你已经获取到了JSON数据 url = "你的Bittrex数据URL" response = urllib2.urlopen(url) data = json.load(response) # 整理OHLC和成交量数据 ohlc_data = [] volumes = [] for entry in data['result']: open_price = float(entry['O']) high_price = float(entry['H']) low_price = float(entry['L']) close_price = float(entry['C']) volume = float(entry['V']) # 用索引暂代时间(如果有时间字段可以替换成时间戳/日期) ohlc_data.append([len(ohlc_data), open_price, high_price, low_price, close_price]) volumes.append(volume)
第二步:创建双图布局并绘图
接下来用plt.subplots创建上下两个子图,共享x轴保证联动,然后分别绘制K线和成交量:
# 创建上下布局的子图,K线图高度是成交量的3倍 fig, (ax_kline, ax_volume) = plt.subplots( 2, 1, figsize=(12, 8), sharex=True, gridspec_kw={'height_ratios': [3, 1]} ) # 绘制K线图 candlestick2_ohlc( ax_kline, [x[1] for x in ohlc_data], # 开盘价 [x[2] for x in ohlc_data], # 最高价 [x[3] for x in ohlc_data], # 最低价 [x[4] for x in ohlc_data], # 收盘价 width=0.6, colorup='green', colordown='red' ) ax_kline.set_title('Bittrex 加密货币K线图(带成交量)') ax_kline.set_ylabel('价格') ax_kline.grid(True) # 给成交量柱子按涨跌上色(涨绿跌红) bar_colors = [] for idx in range(len(ohlc_data)): if ohlc_data[idx][4] >= ohlc_data[idx][1]: bar_colors.append('green') else: bar_colors.append('red') # 绘制成交量柱状图 ax_volume.bar( range(len(volumes)), volumes, color=bar_colors, width=0.6 ) ax_volume.set_ylabel('成交量') ax_volume.set_xlabel('时间') ax_volume.grid(True) # 如果有时间字段,可以替换x轴刻度为日期(示例) # import datetime # time_stamps = [datetime.datetime.strptime(entry['T'], '%Y-%m-%dT%H:%M:%S') for entry in data['result']] # ax_volume.set_xticks(range(len(time_stamps))) # ax_volume.set_xticklabels([t.strftime('%Y-%m-%d %H:%M') for t in time_stamps], rotation=45) # 调整布局避免标签重叠 plt.tight_layout() plt.show()
关键细节说明
- 共享x轴:
sharex=True让K线图和成交量图的x轴联动,缩放或平移时两个图同步,符合看盘习惯。 - 涨跌配色:成交量柱子的颜色和K线涨跌一致,能更直观地看出量价关系。
- 布局比例:
height_ratios设置K线图高度是成交量的3倍,这是金融图表的常规布局,重点突出价格走势。
这样修改后,你就能同时看到K线走势和对应的成交量变化啦~
内容的提问来源于stack exchange,提问作者user9280506




