【问题标题】:Adding labels to candlestick series为烛台系列添加标签
【发布时间】:2014-04-08 07:13:29
【问题描述】:

以下代码 sn-p 绘制了两个烛台系列,每根 4 根柱线:

from pylab import * 
from matplotlib.finance import candlestick
import matplotlib.gridspec as gridspec

quotes = [(734542.0, 1.326, 1.3287, 1.3322, 1.3215), (734543.0, 1.3286, 1.3198, 1.3292, 1.3155), (734546.0, 1.321, 1.3187, 1.3284, 1.3186), (734547.0, 1.3186, 1.3133, 1.3217, 1.308)]
quotes2 = [(734542.0, 1.0, 0.9979, 1.0046, 0.9953), (734543.0, 0.998, 0.9991, 1.0024, 0.9952), (734546.0, 0.9991, 1.0014, 1.0038, 0.9951), (734547.0, 1.003, 1.0028, 1.0047, 1.0002)]

fig, ax = subplots()
candlestick(ax,quotes,width = 0.5, colorup = "green", colordown = "red")
candlestick(ax,quotes2, width = 0.2, colorup = "grey", colordown = "black")
ax.xaxis_date()
ax.autoscale_view()
ax.legend(loc=3)


plt.show()

我无法为这两个系列添加标签,并且在网络上我还没有找到任何东西。这样做的正确语法是什么?

candlestick(ax,quotes,width = 0.5, label = "Series 1") #but it doesn't work

注意:我需要的不是在特定点上注释某些内容,例如 this 或其他线程解释,而是要添加到图表图例中的适当标签,因为最终目的是绘制几个标准化的价格序列,以便在视觉上相互比较。

添加:更准确地说,“但它不起作用”的粗略尝试确实不适用于以下预期错误:

TypeError: candlestick() got an unexpected keyword argument 'label'

【问题讨论】:

  • 不幸的是,我认为不支持此功能(请参阅here)。您可以做的最好的事情是为每个烛台图创建一个 Text 对象。
  • @Ffisegydd 是的,他们似乎还没有考虑过烛台图的图例......但请参阅下面的解决方案,它不是 100% 正确的烛台图例,但它似乎是一个非常好的解决方案不过!

标签: python matplotlib candlestick-chart


【解决方案1】:

您需要更改几个地方来获取标签:

C1=candlestick(ax,quotes,width = 0.5, colorup = "green", colordown = "red")
C2=candlestick(ax,quotes2, width = 0.2, colorup = "grey", colordown = "black")
ax.xaxis_date()
ax.autoscale_view()
ax.legend((C1[1][0],C2[1][0]), ('label1', 'label2'),loc=3)

问题是我们这里有colorupcolordown,你不能轻易地将它们都放在图例中(好吧,你也许可以,那会很复杂)。

那么为什么是C2[1][0]?因为这就是C1 是:

In [5]:

C1
Out[5]:
([<matplotlib.lines.Line2D at 0x76b3c90>,
  <matplotlib.lines.Line2D at 0x759d3b0>,
  <matplotlib.lines.Line2D at 0x759dab0>,
  <matplotlib.lines.Line2D at 0x75a61d0>],
 [<matplotlib.patches.Rectangle at 0x76b3df0>,
  <matplotlib.patches.Rectangle at 0x759d590>,
  <matplotlib.patches.Rectangle at 0x759dc90>,
  <matplotlib.patches.Rectangle at 0x75a63b0>])

如果您有其他将遵循烛台图的图:

plt.hlines(1.10, plt.xlim()[0], plt.xlim()[1], label='Other Plot') #such as an horizontal line
#And may be other plots.
handles, labels = ax.get_legend_handles_labels()
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1)) #sort is optional
handles2, labels2 = zip(*hl)
handles2=list(handles2)+[C1[1][0],C2[1][0]] #put the candel plot legend to the end
labels2=list(labels2)+['label1', 'label2'] #put the candel plot legend to the end
ax.legend(handles2, labels2, loc=8)

取自documents

【讨论】:

  • 这正是我想要的。伟大的!这个问题肯定回答了,我借机问你一个我需要的细节:这个图表系统,除了绘制烛台系列,还会绘制其他曲线(如指标),它的图例是在后期创建的,所以是覆盖原来的。你会如何建议继续加入所有的传奇?由于我正在标记 Rectangle 对象,我希望传说是联合的?
  • 我猜你最终会制作传奇,请参阅编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多