函数中返回的散景图未渲染

Bokeh plot returned in function not rendering

我正在编写一个函数来简化我的绘图,当我调用

时它还没有给出任何错误

show(plt)

在 return 值上没有任何反应。我在 Jupyter 笔记本上工作。我已经打电话给:

output_notebook()

函数代码如下:

def plot_dist(x, h, title, xl="X axis", yl="Y axis", categories=None, width=0.5, bottom=0, color="#DC143C", xmlo=None, ymlo=None, xlo=-18, ylo=5):
    total = np.sum(h)
    source = ColumnDataSource(data={
        "x":x,
        "h":h,
        "percentages":[str(round((x*100)/total, 2)) + "%" for x in h]
    })
    plt = figure(
        title=title,
        x_axis_label=xl,
        y_axis_label=yl
    )
    plt.vbar(
        x="x",
        width=width,
        bottom=bottom,
        top="h",
        source=source,
        color=color
    )
    if xmlo is None:
        if categories is None:
            raise ValueError("If no categories are provided xaxis.major_label_overrides must be defined")
        plt.xaxis.major_label_overrides = {
            int(x):("(" + str(c.left) + "-" + str(c.right) + "]") for x,c in enumerate(categories)
        }
    else:
        plt.xaxis.major_label_overrides = xmlo

    if ymlo is None:
        plt.yaxis.major_label_overrides = { int(x):(str(int(x)/1000)+"k") for x in range(0, h.max(), math.ceil((h.max()/len(h))) )}
    else:
        plt.yaxis.major_label_overrides = ymlo

    labels = LabelSet(
        x=str(x), y=str(h), text="percentages", level="glyph",
        x_offset=xlo, y_offset=ylo, source=source, render_mode="canvas"
    )
    plt.add_layout(labels)

    return plt   

这就是它的调用方式:

X = [x for x in range(0, len(grps.index))]
H = grps.to_numpy()
plt = plot_dist(X, H, "Test", "xtest", "ytest", grps.index.categories)

X 只是一个列表,grps 是调用 pandas' DataFrame.groupby

的结果

正如我所说,它不会给出任何错误,所以我认为问题出在 ColumnDataSource 对象上,我一定是创建错误了。任何帮助表示赞赏,谢谢!

编辑 1:显然删除以下行解决了问题:

plt.add_layout(labels)

绘图现在正确呈现,但我需要添加标签,知道吗?

编辑 2:好的,我已经解决了问题,当 运行 代码显示以下错误时检查 Web 控制台:

Error: attempted to retrieve property array for nonexistent field

问题出在以下几行:

    labels = LabelSet(
        x=str(x), y=str(h), text="percentages", level="glyph",
        x_offset=xlo, y_offset=ylo, source=source, render_mode="canvas"
    )

特别是分配 x=str(x)y=str(h)。将其更改为简单的 x="x"y="h" 解决了它。

代码的问题在于标签声明:

labels = LabelSet(
    x=str(x), y=str(h), text="percentages", level="glyph",
    x_offset=xlo, y_offset=ylo, source=source, render_mode="canvas"
)   

它是通过检查浏览器的 Web 控制台发现的,它给出了以下错误:

Error: attempted to retrieve property array for nonexistent field

参数 xy 必须引用传递给 Glyph 方法的 ColumnDataSource 对象中的名称,用于绘制绘图。
我错误地传递了 str(x)str(y),它们是内容的字符串表示形式。我错误地假设它会引用变量的字符串表示形式。
要解决此问题,只需将 ColumnDataSource 构造函数中使用的字典键作为值传递给 LabelSet 构造函数的 xy 参数即可:

labels = LabelSet(
    x="x", y="h", text="percentages", level="glyph",
    x_offset=xlo, y_offset=ylo, source=source, render_mode="canvas"
)   

此外,如果 ColumnDataSource 是从 DataFrame 构建的,则字符串将是列名、字符串 "index",如果图中使用的任何数据都参考到索引,这没有明确的名称,或索引对象的名称。

非常感谢 bigreddot 帮助我解决问题和回答。