【问题标题】:How to align data points and tick labels?如何对齐数据点和刻度标签?
【发布时间】:2020-12-28 10:39:13
【问题描述】:

我想画一个带圆圈的网格并标记每一行和每一列。虽然我可以绘制数据点,但我无法正确对齐数据点及其各自的标签,所以绘图如下所示:

如何正确完成,使刻度标签与数据点对齐?

代码:

import numpy as np
import itertools
from bokeh.models import Circle, ColumnDataSource
from bokeh.plotting import figure, show

space = 0.5
row_ind = np.arange(0, 2, space)
col_ind = np.arange(0, 1.5, space)

data_points = list(itertools.product(row_ind, col_ind))

rows = [dp[0] for dp in data_points] 
cols = [dp[1] for dp in data_points]
size = 10
sizes = [size] * len(data_points)
source = ColumnDataSource(dict(columns=cols, rows=rows, size=sizes))

plot = figure(
    plot_width=400,
    plot_height=300,
    x_range=["1", "2", "3"],
    y_range=list("ABCD")
)
plot.circle(
    x="columns",
    y="rows",
    size="size",
    line_color="black",
    fill_color="white",
    line_width=2,
    source=source
)
show(plot)

【问题讨论】:

    标签: python bokeh


    【解决方案1】:

    您应该使用散景中的默认范围,然后使用plot.xaxis.tickerplot.yaxis.tickerplot.yaxis.major_label_overrides 更改刻度。

    完整示例

    import numpy as np
    import itertools
    from bokeh.models import Circle, ColumnDataSource
    from bokeh.plotting import figure, show, output_notebook
    output_notebook()
    row_ind = np.arange(0, 2, 0.5)
    col_ind = np.arange(0, 1.5, 0.5)
    
    data_points = list(itertools.product(row_ind, col_ind))
    rows = [dp[0] for dp in data_points] 
    cols = [dp[1] for dp in data_points]
    sizes = [10] * len(data_points)
    
    source = ColumnDataSource(dict(columns=cols, rows=rows, size=sizes))
    plot = figure(
        plot_width=400,
        plot_height=300
    )
    plot.circle(
        x="columns",
        y="rows",
        size="size",
        line_color="black",
        fill_color="white",
        line_width=2,
        source=source
    )
    plot.xaxis.ticker, plot.yaxis.ticker = col_ind, row_ind
    plot.yaxis.major_label_overrides = dict(zip(
        [int(i) if i.is_integer() else i for i in row_ind], 
        list('ABCD'))
       )
    show(plot)
    

    输出

    【讨论】:

    • 谢谢!但是,我不能重现这个情节。 row_indcol_ind 需要在你的代码中切换,我认为)。然后当我使用这个major_label_overrides 时,我得到了数字和字母的混合。我使用:plot.xaxis.ticker = col_indplot.yaxis.ticker = row_ind,然后是plot.yaxis.major_label_overrides = {i:s for i,s in zip(row_ind, list('ABCD'))},但那让我然后0B1D 作为刻度标签,AC 被忽略。你能发布你的完整代码和你正在使用的散景版本吗?我已经投了赞成票,因为这给了我一些可以玩的东西;一旦它起作用,我就接受......
    • 好的,解决了;似乎是here 描述的错误。作为一种解决方法,我现在添加了row_ind = [ int(item) if float(item).is_integer() else item for item in row_ind ]col_ind 相同),然后解决了这个问题。您对此有更直接的解决方案吗?
    • 我没有发现这个错误,我使用自定义字典 ​​{0.5:'A', 1:'B', 1.5:'C', 2:'D'} 和预计可以使用其他解决方案。我更新了我的答案并现在显示完整的代码。我无法避免您提到的解决方法。
    猜你喜欢
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 2021-06-14
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多