欢迎访问宙启技术站
智能推送

Python中使用Bokeh绘制瀑布图的示例

发布时间:2024-01-03 15:03:57

Bokeh是一个用于交互式数据可视化的Python库,它提供了丰富的绘图工具和交互功能。在Bokeh中,可以使用水平条形图和竖直条形图绘制瀑布图。

水平瀑布图示例:

下面是一个使用Bokeh绘制水平瀑布图的示例,该示例展示了销售额的变化。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.palettes import Spectral6

output_file("waterfall.html")

data = {'categories': ['Q1', 'Q2', 'Q3', 'Q4'],
        'amounts': [500, -300, 200, -150],
        'colors': Spectral6}

source = ColumnDataSource(data)

p = figure(y_range=data['categories'], plot_width=600, plot_height=400, 
           title="Sales Waterfall")

p.hbar(y='categories', left=0, right='amounts', height=0.8, fill_color='colors', 
       source=source)

p.x_range.start = -400
p.x_range.end = 600

p.ygrid.grid_line_color = None
p.xaxis.axis_label = "Sales Amount ($)"
p.xaxis.formatter.use_scientific = False

show(p)

这个示例中,我们首先导入所需要的Bokeh模块和绘图工具。然后,我们定义了要绘制的数据,包括销售季度、销售额和颜色。接下来,我们创建了一个ColumnDataSource对象,用于存储数据。

然后,我们创建了一个绘图对象p,并设置了绘图的参数,包括标题、尺寸、数据源等。在这个示例中,我们使用了hbar()方法绘制水平条形图,通过设置y参数为'categories',left参数为0,right参数为'amounts',以及height参数为0.8,可以绘制出水平瀑布图。我们还通过设置fill_color参数为'colors',使用了一个颜色调色板来为每个条形图的颜色赋值。最后,我们通过设置x_range的起始值和结束值来调整x轴的显示范围。

最后,我们调用show()方法显示绘图。

竖直瀑布图示例:

下面是一个使用Bokeh绘制竖直瀑布图的示例,该示例展示了收入和支出的变化。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.palettes import Spectral

output_file("waterfall.html")

data = {'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        'revenue': [1000, 1200, 1500, 1300, 1100, 1400, 1600, 1800, 1900, 1700, 1600, 1800],
        'expenses': [-500, -200, -300, -400, -600, -500, -400, -300, -400, -600, -500, -400]}

source = ColumnDataSource(data)

p = figure(x_range=data['categories'], plot_width=800, plot_height=400, 
           title="Income and Expenses Waterfall")

p.vbar_stack(['revenue', 'expenses'], x='categories', width=0.9, color=Spectral[2:4], 
             source=source, legend_label=['Revenue', 'Expenses'])

p.y_range.start = -2000
p.y_range.end = 2000

p.ygrid.grid_line_color = None
p.xaxis.axis_label = "Months"
p.yaxis.axis_label = "Amount ($)"

p.legend.location = "top_left"
p.legend.orientation = "vertical"

show(p)

这个示例中,我们首先导入所需要的Bokeh模块和绘图工具。然后,我们定义了要绘制的数据,包括月份、收入和支出。接下来,我们创建了一个ColumnDataSource对象,用于存储数据。

然后,我们创建了一个绘图对象p,并设置了绘图的参数,包括标题、尺寸、数据源等。在这个示例中,我们使用了vbar_stack()方法绘制竖直条形图,通过设置x参数为'categories',width参数为0.9,color参数为一个颜色调色板,source参数为我们定义的数据源,可以绘制出竖直瀑布图。我们将'revenue'和'expenses'作为堆叠的条形图,分别表示收入和支出。同时,我们在legend_label参数中设置了图例标签。

最后,我们调用show()方法显示绘图。

使用Bokeh绘制瀑布图可以方便地展示数据的变化,通过颜色和条形图的堆叠,可以直观地比较不同数据的差异。