我正在处理Bokeh情节,并且几乎以我想要的方式得到它。但是,我正努力添加多行轴标签。
这是我到目前为止所拥有的:
import bokeh.io
from bokeh.plotting import gridplot, figure, output_file, show, output_notebook
from bokeh.models import ColumnDataSource, BoxAnnotation, CategoricalAxis, FactorRange
from bokeh.embed import components
x = ['label1','label2','label3','label4','label5','label6','label7', 'Trying for a multiline label']
y = [1.0, 2.7, 1.2, 4.5, 1.5, 2.2, 1.8, 4.6]
p = figure(x_range=[*x], y_range=(0, 5), plot_height=400, plot_width=550)
dots = p.circle(x=x, y=y, color='black',size=10)
line = p.line(x=x, y=y, color='black')
numbers = [str(x) for x in y]
p.extra_x_ranges = {"extra_numbers": FactorRange(factors=numbers)}
p.add_layout(CategoricalAxis(x_range_name="extra_numbers"), 'below')
p.title.text = 'Plot'
p.title.text_font_size = "25px"
p.title.text_color = "black"
p.title.align = "center"
low_box = BoxAnnotation(top=2, fill_alpha=0.1, fill_color='green')
mid_box = BoxAnnotation(bottom=2, top=3, fill_alpha=0.1, fill_color='orange')
high_box = BoxAnnotation(bottom=3, fill_alpha=0.1, fill_color='red')
p.add_layout(low_box)
p.add_layout(mid_box)
p.add_layout(high_box)
show(p)
您可以清楚地看到最后一个标签没有正确包装,并且我还没有弄清楚如何包装和创建多行轴标签。是否有捷径可寻?我想到的最好的替代解决方案是尝试使用垂直标签,但是如您所见,它们看起来不太好,并且弄乱了文本下方的第二个轴:
from bokeh.models import CategoricalAxis, FactorRange
from bokeh.plotting import figure, show
from math import pi
x = ['label1','label2','label3','label4','label5','label6','label7', 'Trying for a multiline label']
y = [1.0, 2.7, 1.2, 4.5, 1.5, 2.2, 1.8, 4.6]
p = figure(x_range=[*x], y_range=(0, 5), plot_height=900)
dots = p.circle(x=x, y=y, color='black',size=10)
line = p.line(x=x, y=y, color='black')
p.xaxis.major_label_orientation = pi/2
p.xaxis.major_label_text_font_size = "1.4em"
p.xaxis.axis_line_width = 2
p.yaxis.axis_line_width = 2
numbers = [str(x) for x in y]
p.extra_x_ranges = {"extra_numbers": FactorRange(factors=numbers)}
p.add_layout(CategoricalAxis(x_range_name="extra_numbers"), 'below')
show(p)
当然,一个简单的解决方法是切换轴的顺序,以使数字在顶部,标签在下面;但是,这仍然是一个偶然的解决方案,并不是我真正想要的。我真的很想标签中的文字换行。例如,下面的图类似于我要完成的事情(下面的非散景图代码可在here中找到)。
任何帮助或建议将不胜感激!
答案 0 :(得分:1)
库存散景轴模型无法使用多行标签。为了实现这一点,您必须创建一个自定义的Axis
子类并自己管理所有包装,因为canvas
上下文不以任何方式支持它。
您也可以尝试使用倾斜标签。这种方法的缺点是必须找出绘图的正确偏移量,以确保标签不会被切除。