在对csv进行一些转换后,我有一个数据帧:
ENTRYDATE | TRANSACTIONS
2017/05/01 5
2017/05/02 20
..
2018/02/05 15
我将它转换为pandas中的datetime并使用
工具提示创建一个行图import pandas as pd
from bokeh.models import ColumnDataSource,DatetimeTickFormatter, NumeralTickFormatter, HoverTool
from bokeh.plotting import figure
from bokeh.io import curdoc
df=pd.read_csv(r'C:\Users\file.csv')
df2=df[['ENTRYDATE']]
df2['ENTRYDATE']=pd.to_datetime(df2['ENTRYDATE'],infer_datetime_format=True)
df2=(df2.groupby([df2['ENTRYDATE'].dt.date]).size().reset_index(name='Transactions'))
#print(df2)
#print(df2.info())
source=ColumnDataSource(data=df2)
#hovertool
p=figure(plot_width=800,plot_height=500)
hover=HoverTool(tooltips=[("Date","@ENTRYDATE"),("Transactions","@Transactions")],
formatters={"ENTRYDATE":"datetime"},
mode='vline')
p.add_tools(hover)
p.scatter(x="ENTRYDATE",y="Transactions",color='blue', source=source)
p.xaxis.formatter=DatetimeTickFormatter()
p.yaxis.formatter=NumeralTickFormatter(format="0")
curdoc().add_root(p)
出于某种原因,显示ENTRYDATE的工具提示实际上并不显示日期(即2017-05-01
),而是显示一些长数字(即14962752000000
)。有人可以告诉我如何编辑这个以便工具提示以日期格式显示日期吗?
答案 0 :(得分:1)
您需要在formatters
dict中告诉它 CDS列名,并且还需要为该字段指定所需的实际特定日期时间格式,例如
HoverTool(tooltips=[
("Date", "@ENTRYDATE{%F}"), # must specify desired format here
("Transactions", "@Transactions")
], formatters={"ENTRYDATE":"datetime"}, mode='vline')
答案 1 :(得分:0)
另一种方法是将日期转换为字符串作为单独的列。从Yahoo获取一些库存数据。我有以下代码
import pandas as pd
# use bp as bokeh plot
from bokeh.plotting import figure, output_file, show
from bokeh.models import Range1d, HoverTool, ColumnDataSource
# get the datetime library for date & time calcs
from datetime import datetime, timedelta
data = pd.read_csv("DJI.csv")
data.head()
然后执行以下绘图:
# clean up the date fields to become dates
data['Date'] = pd.to_datetime(data['Date'], format='%Y-%m-%d')
# create a string column for plotting
data["DateString"] = data["Date"].dt.strftime("%Y-%m-%d")
# work on the bokeh plot
# set the data source for the plots and hover tool
cds = ColumnDataSource(data)
bp = figure(width=500, height=250, x_axis_type="datetime", sizing_mode="scale_width")
# bp.x_range = Range1d(bounds=(2015-12-31, 2018-12-28))
# make the hover tool and add it
hover = HoverTool(tooltips = [("Date","@DateString"),("Close", "@Close")])
bp.add_tools(hover)
bp.line("Date", "Close", color = "Red", alpha = 0.5, source = cds)
output_file("Timeseries.html")
show(bp)