LoginSignup
2
1

More than 1 year has passed since last update.

bokeh: 凡例のフォントサイズを小さくして、できるだけ多くの項目を表示する

Last updated at Posted at 2022-07-11

環境

  • Python 3.10.2
  • bokeh 2.4.3

やりたいこと

Pythonのbokehライブラリを使って、グラフを描画しています。

以下のようなコードで、グラフに20個以上の折れ線を表示したいです。

import bokeh
import bokeh.palettes
import numpy
from bokeh.plotting import figure, output_file, save

output_file("graph.html")

x_data = numpy.arange(-20, 20, 0.1)
palette = bokeh.palettes.Category20[20]

fig = figure(x_axis_label="x", y_axis_label="y", height=400)

for i in range(20):
    fig.line(
        x_data, numpy.sin(x_data + i), color=palette[i], legend_label=f"y=sin(x + {i})"
    )

save(fig)

image.png

折れ線は20個表示されたのですが、凡例の項目は14個までしか表示されませんでした。

グラフサイズを変えずに、凡例にできるだけ多くの項目を表示したいです。
凡例の項目を複数列で表示できれば解決するのですが、2022年7月現在、bokehは対応していません。

bokeh3.1で、legendでncol,nrowが利用できるようになりました。
https://github.com/bokeh/bokeh/issues/3880

そこで、フォントサイズを可能な限り小さくして、できるだけ多くの項目を凡例に表示するようにします。

解決

以下のコードを追記すれば、凡例に20個の項目が表示されます

fig.legend.label_text_font_size = "9px"
fig.legend.label_height = 10
fig.legend.glyph_height = 10
save(fig)

image.png

フォントサイズだけではなく、凡例の項目の高さを小さくする必要があります。
fig.legend.label_text_font_size = "9px"のみ指定した場合は、下図のように凡例に表示される項目数は増えません。
image.png

なお、各プロパティの説明は以下の通りです。

label_text_font_size : The text font size for the legend labels.
label_height : The minimum height (in pixels) of the area that legend labels should occupy.
glyph_height : The height (in pixels) that the rendered legend glyph should occupy.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1