Skip to main content
 首页 » 编程设计

python之使用 Matplotlib v2.2.2 的烛台图表

2024年12月31日8zfyouxi

<分区>

我注意到在 Matplotlib API 版本 2.2.2 中,matplotlib.finance 不再可用。过去那是我用来创建烛台图表的。

随着 matplotlib.finance 的消失,我读到推荐的方法是使用 matplotlib.axes.bar?

在 python 中是否有更好的方法来构建烛台图表?我一直认为 matplotlib 是绘图的首选,但它似乎并没有直接用于构建烛台图表的功能。

否则,我的代码看起来如何?除了糟糕的配色方案。

import numpy as np 
import matplotlib.pyplot as plt 
 
## OHLC Data 
open =  np.array([479.09, 499.11, 478.96, 468.63, 449.13, 460.74, 457.99, 449.52, 479.33, 471.89]) 
high =  np.array([511.67, 515.28, 484.36, 469.94, 468.90, 471.88, 470.60, 484.52, 485.28, 484.87]) 
low =   np.array([465.14, 469.17, 462.64, 439.52, 441.37, 455.00, 446.00, 448.62, 464.28, 458.74]) 
close = np.array([499.11, 478.97, 468.64, 449.13, 460.74, 457.99, 449.60, 479.33, 471.89, 462.30]) 
 
 
 
n_groups = open.size            # number of bars 
index = np.arange(n_groups)     # evenly space each bar 
 
## Create Plot Figure 
fig, ax = plt.subplots() 
 
## Translate OHLC Data to Bar Graph Data 
bar_height = np.absolute(open - close) 
bar_bottom  = np.minimum(open, close) 
 
yerr_high = high - np.maximum(open,close) 
yerr_low =  np.minimum(open,close) - low + bar_height 
 
bar_width = 0.5 
 
## Color 
 
 
## Set Chart Alpha Levels 
opacity = 1 
error_config = {'alpha': opacity} 
 
rects1 = ax.bar( 
            index,                                 # X Coordinate of bars 
 
            bar_height,                            # [Largest Price,] (Open/Close) 
            bar_width,                             # bar width 
            bar_bottom,                            # [Smallest Price,] (Open/Close) 
            alpha = opacity,                       # bar alpha level 
 
            error_kw = error_config,               # kwargs to be passed to the errorbar method 
            yerr = [yerr_low, yerr_high]           # error bar [Low Price, ], [High Price, ] 
            ) 
 
## Set Chart Axis and Title 
ax.set_xlabel('Date') 
ax.set_ylabel('Price') 
ax.set_title('Candlestick Chart') 
ax.set_xticks(index) 
 
## Plot Chart 
fig.tight_layout() 
plt.show()