我正在尝试通过熊猫与Bokeh绘制一些数据。 x轴是日期,我可以让Bokeh正确地“大部分”绘制轴(范围可能不正确)。但是,它输出的行到处都是。
例如:
看起来好像是一条大而连续的线?
这是我的代码:
# library imports
import pandas as pd
from bokeh.io import output_file, show, vform
from bokeh.plotting import figure, output_file, ColumnDataSource, show
from bokeh.models import HoverTool, BoxAnnotation, BoxSelectTool, BoxZoomTool, WheelZoomTool, ResetTool
# Import csv into pandas dataframe
df = pd.read_csv(r"C:\Users\paul.shapiro\Documents\kwdata.csv", parse_dates=['Interest over time_time'])
df.rename(columns={'Search Term': 'keyword', 'Interest over time_time': 'date', 'Weekly Volume': 'volume'}, inplace=True)
source = ColumnDataSource(data=dict(x=df['date'], y=df['volume'], desc=df['keyword']))
TOOLS = [HoverTool(tooltips=[("Keyword", "@desc"),("Date", "@x"),("Search Volume", "@y")]), BoxZoomTool(), WheelZoomTool(), ResetTool()]
# Output html for embedding
output_file("line.html")
p = figure(plot_width=800, plot_height=800, tools=TOOLS, x_axis_type="datetime")
# add both a line and circles on the same plot
p.line(df['date'], df['volume'], line_width=2, color=df['keyword'], source=source)
p.circle(df['date'], df['volume'], fill_color="white", size=8, source=source)
show(p)
有趣的是,如果您使用bokeh.charts对其进行绘制(如果我这样做,则工具提示将不起作用,因此不是一种选择,它可以很好地绘制:
defaults.width = 800
defaults.height = 800
TOOLS = [BoxZoomTool(), WheelZoomTool(), ResetTool()]
line = Line(df, x='date', y='volume', color='keyword', source=source, tools=TOOLS)
show(line)
output_file("line.html", title="Search Volume")
任何帮助将不胜感激。这让我发疯了!
SOLVED使用multi_line()和for循环:
import pandas as pd
from bokeh.io import output_file, show, vform
from bokeh.plotting import figure, output_file, ColumnDataSource, show
from bokeh.models import HoverTool, BoxAnnotation, BoxSelectTool, BoxZoomTool, WheelZoomTool, ResetTool
df = pd.read_csv(r"C:\Users\paul.shapiro\Documents\kwdata.csv", parse_dates=['Interest over time_time'])
df.rename(columns={'Search Term': 'keyword', 'Interest over time_time': 'date', 'Weekly Volume': 'volume'}, inplace=True)
gp = df.groupby('volume')
source = ColumnDataSource(data=dict(x=df['date'], y=df['volume'], desc=df['keyword']))
TOOLS = [HoverTool(tooltips=[("Keyword", "@desc"),("Date", "@x"),("Search Volume", "@y")]), BoxZoomTool(), WheelZoomTool(), ResetTool()]
p = figure(plot_width=800, plot_height=800, tools=TOOLS, x_axis_type="datetime")
gp = df.groupby('keyword')
# groups() returns a dict with 'Gene':indices as k:v pair
for g in gp.groups.items():
p.multi_line(xs=[df.loc[g[1], 'date']], ys=[df.loc[g[1], 'volume']])
p.circle(df['date'], df['volume'], fill_color="white", size=8, source=source)
output_file("newline.html")
show(p)
我看不到您的代码有什么问题。尝试根据bokeh示例,从简单的嵌套值列表中查看数据帧df有何不同。也许通过对数据框进行一些操作就可以使此工作正常。
http://docs.bokeh.org/en/latest/docs/reference/plotting.html
from bokeh.plotting import figure, output_file, show
p = figure(plot_width=300, plot_height=300)
p.multi_line(xs=[[1, 2, 3], [2, 3, 4]], ys=[[6, 7, 2], [4, 5, 7]],
color=['red','green'])
show(p)