代码之家  ›  专栏  ›  技术社区  ›  pankaj mishra

在Bokeh中将“string”类型转换为“int”时,无法正确绘制图形

  •  1
  • pankaj mishra  · 技术社区  · 8 年前

    我正在从xml中获取一些属性值,这些属性值本质上是数字的,但类型为“string”

    我正在转换这些 '字符串' 键入到 “int” ,并尝试在Bokeh中绘制条形图。 图形填充不正确(附件) Bokeh Graph . 有什么建议吗?

    下面是代码

    import pandas as pd
    from bokeh.charts import Bar, output_file, show
    #String values fetched from xml
    var='5'
    var1='6'
    #Converting string to int
    var=int(var)
    var1=int(var1)
    
    #Creating a dataframe
    d = {'col1': [var], 'col2': [var1]}
    df=pd.DataFrame(data=d)
    print df
    
    #Output
    #   col1  col2
    #0     0     4
    
    #Displaying with Bokeh
    
    p=Bar(df)
    output_file("bar.html")
    show(p)
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   bigreddot    8 年前

    首先: Bar 是旧的、不推荐的 bokeh.charts 从核心Bokeh中完全删除的API。它仍然可用作 bkcharts . 此时不应将其用于任何新工作。


    然而,最近的工作使用稳定、支持的 bokeh.plotting 应用程序编程接口。有 large new User's Guide Section 纯粹致力于解释和演示多种条形图,既简单又复杂。此外,现在条形图很容易使用标准 博克。绘图 通话 general guidance and documentation for hover tools 现在也适用。

    从您的示例代码中,我不太清楚您试图实现什么。下面是一个非常精简的版本,可能与此类似:

    from bokeh.io import output_file, show
    from bokeh.plotting import figure
    
    p = figure(x_range=['col1', 'col2'])
    p.vbar(x=['col1', 'col2'], top=[5, 6], width=0.8)
    
    output_file("bar.html")
    show(p)
    

    该代码生成以下输出:

    enter image description here

    下面是一个使用pandas统计数据的简单条形图的更完整示例(类似于 酒吧 可以)使用“cars”样本数据和 博克。绘图 应用程序编程接口:

    from bokeh.io import show, output_file
    from bokeh.models import HoverTool
    from bokeh.plotting import figure
    from bokeh.sampledata.autompg import autompg as df
    
    output_file("groupby.html")
    
    df.cyl = df.cyl.astype(str)
    group = df.groupby('cyl')
    
    p = figure(plot_height=350, x_range=group, toolbar_location=None, tools="")
    p.vbar(x='cyl', top='mpg_mean', width=0.9, source=group)
    
    p.add_tools(HoverTool(tooltips=[("Avg MPG", "@mpg_mean")]))
    
    show(p)
    

    这将产生以下结果

    enter image description here