图中只显示了红蜡烛

2024-09-29 01:28:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Bokeh,我正在尝试从一个熊猫数据框在烛台图表中绘制一个数据。然后将鼠标悬停在蜡烛上查看数据。在下面的代码中,我只看到红蜡烛(open>;close)用于悬停,而不是(open<;close)>;不确定问题出在哪里。在

请告诉我这是什么问题。在

from math import pi

import pandas as pd

from bokeh.models.formatters import TickFormatter, String, List
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.stocks import MSFT
from bokeh.models import ColumnDataSource, HoverTool

# create a custom model for a new tick formatter
class DateGapTickFormatter(TickFormatter):
    ''' A custom TickFormatter useful for skipping dates
    Axis labels are taken from an array of date strings
    (e.g. ['Sep 01', 'Sep 02', ...]) passed to the ``date_labels``
    property.
    '''
    date_labels = List(String, help="""
    An array of date strings to map integer date indices to.
    """)

    __implementation__ = """
        import {Model} from "model"
        import * as p from "core/properties"
        export class DateGapTickFormatter extends Model
          type: 'DateGapTickFormatter'
          doFormat: (ticks) ->
            date_labels = @date_labels
            return (date_labels[tick] ? "" for tick in ticks)
          @define {
            date_labels: [ p.Any ]
          }
    """



df = pd.DataFrame(MSFT)[:100]

# xaxis date labels used in the custom TickFormatter
date_labels = [date.strftime('%b %d') for date in pd.to_datetime(df["date"])]

inc = df.close > df.open
dec = df.open > df.close
w = 0.5

TOOLS = "pan,hover,wheel_zoom,box_zoom,reset,save"

p = figure(tools=TOOLS, plot_width=1000, title="MSFT Candlestick with Custom X-Axis")

hover = p.select(dict(type=HoverTool))
hover.mode ="mouse"
#hover.names = ['vbar1','vbar2']
hover.tooltips=[
                ( 'Date', '@date' ),
                ( 'Close','@close{0.2f}' ),
              # ( 'Open', '@open{0.2f}'),
              #  ( 'High','@High{%0.2f}'),
              #  ( 'Low', '@Low{%0.2f}'),     
              # ( 'Delta',  '@Delta{0.2f}' ),
              # ( 'volume', '@Volume' )
                ]

mysource1 =  ColumnDataSource(df[inc])
mysource2 =  ColumnDataSource(df[dec])


p.xaxis.major_label_orientation = pi/4
p.grid[0].ticker.desired_num_ticks = 6

# use the custom TickFormatter. You must always define date_labels
p.xaxis.formatter = DateGapTickFormatter(date_labels=date_labels)

# x coordinates must be integers. If, for example, df.index are
# datetimes, you should replace them with a integer sequence
p.segment(df.index, df.high, df.index, df.low, color="black")
p.vbar(df.index[inc], w, df.open[inc], df.close[inc], fill_color="#D5E1DD", line_color="black",source=mysource1)
p.vbar(df.index[dec], w, df.open[dec], df.close[dec], fill_color="#F2583E", line_color="black",source=mysource2)

output_file("custom_datetime_axis.html", title="custom_datetime_axis.py example")

show(p)  # open a browser

Tags: fromimportdfforclosedateindexlabels