如何在散景中绘制水平条形图(Python) [英] How to plot Horizontal Bar Chart in Bokeh (Python)

查看:68
本文介绍了如何在散景中绘制水平条形图(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

data = {'Cities': {'Des_Moines': 80.0, 'Lubbock': -300.0, 'Minneapolis': 85.7,
                        'Orange_County': 80.0, 'Salt_Lake_City': 81.8, 'San_Diego': 80.0, 
                        'San_Francisco': -400.0, 'Troy': -400.0, 'Wilmington': -300.0}}

我已经用Seaborn绘制了它,看起来很棒.

I have plotted this using Seaborn and it looks great.

df_data = pd.DataFrame(data).sort_values('Cities', ascending=False)
sns.barplot(x='Cities', y=df_data.index, data=df_data, label='Cities', palette='Greens')

但是,我想使用Bokeh嵌入这是一个Flask网络应用.

However, I'll like to embed this is a Flask web app using Bokeh.

我在Bokeh中找不到horizontal barplot.即使翻转xy轴似乎也不起作用.这是我所做的: *将df_data9x1转换为1x9.但是,我仍然无法获得任何不错的结果.

I couldn't find an horizontal barplot in Bokeh. Even flipping the x and y axis do not seem to work. This is what I've done: * Transposed df_data from 9x1 to 1x9. Yet, I'm still not getting anything remotely nice.

bar = Bar(df_data.transpose(), df_data.columns.tolist(), stacked=False, responsive=True)

script, div = components(bar)

请注意,我仍然没有Horizontal并且category轴已弄乱.

Notice that I still do not have Horizontal and my category axis is messed up.

任何人都可以帮助进一步修改吗?

Can anyone help modify this further?

推荐答案

使用矩形字形非常容易.请注意,当您使用分类值设置y_range时,散景图中这些值的索引从1开始.这就是为什么计数器"j"从1开始的原因.

It's pretty easy to do with rect glyphs. Note that when you set the y_range with categorical values, the indexing of these in the bokeh plot starts at 1. That's why the counter "j" starts at 1.

import numpy as np
import pandas as pd
from bokeh.plotting import figure, show
from bokeh.models import Range1d

data = {'Cities': {'Des_Moines': 80.0, 'Lubbock': -300.0, 'Minneapolis': 85.7,
                        'Orange_County': 80.0, 'Salt_Lake_City': 81.8, 'San_Diego': 80.0, 
                        'San_Francisco': -400.0, 'Troy': -400.0, 'Wilmington': -300.0}}
#df_data = pd.DataFrame(data).sort_values('Cities', ascending=False)
df_data = pd.DataFrame(data).sort(columns='Cities',ascending=False)

this_series = df_data.loc[:,'Cities']

p = figure(width=800, height=600, y_range=this_series.index.tolist())

p.background_fill = "#EAEAF2"

p.grid.grid_line_alpha=1.0
p.grid.grid_line_color = "white"

p.xaxis.axis_label = 'xlabel'
p.xaxis.axis_label_text_font_size = '14pt'
p.xaxis.major_label_text_font_size = '14pt'
#p.x_range = Range1d(0,50)
#p.xaxis[0].ticker=FixedTicker(ticks=[i for i in xrange(0,5,1)])

p.yaxis.major_label_text_font_size = '14pt'
p.yaxis.axis_label = 'ylabel'

p.yaxis.axis_label_text_font_size = '14pt'


j = 1
for k,v in this_series.iteritems():
  print k,v,j
  p.rect(x=v/2, y=j, width=abs(v), height=0.4,color=(76,114,176),
    width_units="data", height_units="data")
  j += 1

show(p)

这篇关于如何在散景中绘制水平条形图(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆