import numpy as np
import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import brewer,d3
# 数据源https://bl.ocks.org/mbostock/3885211
# 原文https://bokeh.pydata.org/en/latest/docs/gallery/brewer.html
data = pd.read_csv('test_data.csv')
xdata = pd.to_datetime(data['date'])
ydata = data.drop('date',axis=1)
# 颜色代码https://bokeh.pydata.org/en/latest/docs/reference/palettes.html
colors = brewer["Accent"][len(ydata.columns)]
def stacked(df, categories):
# 生成图像矩阵(核心)
'''
:param df: 源数据
:param categories: 数据的列名,以list形式
:return:2维图像点生成
'''
areas = dict()
last = np.zeros(len(df[categories[0]]))
for cat in categories:
next = last + df[cat]
areas[cat] = np.hstack((last[::-1], next))
last = next
return areas
areas = stacked(ydata, ydata.columns)
# x轴的2维化
x2 = np.hstack((xdata[::-1], xdata))
# 创建画布
p = figure(plot_width=900, plot_height=500,title='StackedAreaChart',x_axis_type="datetime")
p.grid.minor_grid_line_color = '#eeeeee'
# p.patches([x2]*8, [areas[i] for i in ydata.columns],color=colors, alpha=0.8, line_color=None)
for i in range(len(ydata.columns)):
p.patches([x2], [areas[ydata.columns[i]]],color=colors[i], alpha=0.8, line_color=None,legend = ydata.columns[i])
# 图例的位置
p.legend.location = "bottom_right"
# 图例的字体颜色
p.legend.label_text_color = 'black'
# 图例的背景颜色
p.legend.background_fill_color = "darkgrey"
# 保存在本地
output_file("777.html")
# 输出到显示器上
show(p)
效果图
测试图