這個融合的例子讓我走上了正軌。
import pandas as pd
from pandas import Series
from dateutil.parser import parse
from bokeh.plotting import figure
from bokeh.layouts import row
from bokeh.charts import Bar, output_file, show
from bokeh.charts.attributes import cat, color
from bokeh.charts.operations import blend
output_file("datestats.html")
只是一些樣本數據,隨意改變它,你認爲合適。首先,我不得不將數據轉換爲適當的格式。
# Sample data
vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dates = ["01-01-2015", "02-01-2015", "03-01-2015", "04-01-2015",
"01-02-2015", "02-02-2015", "03-02-2015", "04-02-2015",
"01-03-2015", "02-03-2015", "03-03-2015", "04-03-2015"
]
它看起來像你的日期格式爲「日 - 月 - 年」 - 我用dateutil.parser所以大熊貓將正確識別它。
# Format data as pandas datetime objects with day-first custom
days = []
days.append(parse(x, dayfirst=True) for x in dates)
你也需要它按月分組 - 我用熊貓重採樣下采樣日期,得到相應的價值每個月,併合併成一個數據幀。
# Put data into dataframe broken into min, mean, and max values each for month
ts = Series(vals, index=days[0])
firstmerge = pd.merge(ts.resample('M').min().to_frame(name="min"),
ts.resample('M').mean().to_frame(name="mean"),
left_index=True, right_index=True)
frame = pd.merge(firstmerge, ts.resample('M').max().to_frame(name="max"),
left_index=True, right_index=True)
背景虛化可讓您使用熊貓數據幀的指數圖表的x值, 作爲discussed here 但讓我添加了日期標籤的新列它不喜歡的日期時間值。請參閱下面的時間序列註釋***。
# You can use DataFrame index for bokeh x values but it doesn't like timestamp
frame['Month'] = frame.index.strftime('%m-%Y')
最後我們到圖表部分。就像奧運獎牌榜樣一樣,我們向Bar傳遞了一些參數。 不管你喜歡玩這些玩法,但note,我添加了圖例完全在圖表之外。如果你有很多數據點,它就像它在這裏建立的方式一樣在圖表上非常混亂。
# Main object to render with stacking
bar = Bar(frame,
values=blend('min', 'mean', 'max',
name='values', labels_name='stats'),
label=cat(columns='Month', sort=False),
stack=cat(columns='values', sort=False),
color=color(columns='values',
palette=['SaddleBrown', 'Silver', 'Goldenrod'],
sort=True),
legend=None,
title="Statistical Values Grouped by Month",
tooltips=[('Value', '@values')]
)
# Legend info (displayed as separate chart using bokeh.layouts' row)
factors = ["min", "mean", "max"]
x = [0] * len(factors)
y = factors
pal = ['SaddleBrown', 'Silver', 'Goldenrod']
p = figure(width=100, toolbar_location=None, y_range=factors)
p.rect(x, y, color=pal, width=10, height=1)
p.xaxis.major_label_text_color = None
p.xaxis.major_tick_line_color = None
p.xaxis.minor_tick_line_color = None
# Display chart
show(row(bar, p))
![Bokeh_output](https://i.stack.imgur.com/WLbkq.png)
如果你複製/粘貼此代碼,這就是你會顯示。
如果你自己渲染,或者如果你爲它服務:將鼠標懸停在每塊看到工具提示(值)。
我沒有抽象的一切,我可以(顏色浮現在腦海中)。
這是你想建立的圖表類型,但它似乎是一個不同的圖表風格,將更多informatively顯示數據,因爲堆疊總數(分+的意思+最大)不提供有意義的信息。但我不知道你的數據真的是什麼。
***你可以考慮timeseries chart。這可以消除在繪圖之前完成的一些數據爭奪。
您也可以考慮,而不是grouping your bars堆放其中。這樣你可以很容易地看到每個月的數字。