凡例の項目数
次のコードを実行したときの出力として、正しいものを1つ選べ。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1], label="a")
ax.plot([2], label="b")
print(len(ax.get_legend_handles_labels()[0]))
- A
1 - B
0 - C
4 - D
2
正解と解説を見る
正解:D
label を付けた図形が、凡例の項目になる。get_legend_handles_labels で、項目を確認できる。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import matplotlib.pyplot as plt` | — |
| 2 | `fig, ax = plt.subplots()` | — |
| 3 | `ax.plot([1], label="a")` | — |
| 4 | `ax.plot([2], label="b")` | — |
| 5 | `print(len(ax.get_legend_handles_labels()[0]))` | — |
| 結果 | 実際の出力 | 2 |

- A
誤り。2 本とも
labelが付いている。 - B
誤り。
labelが付いた線がある。 - C
誤り。線の本数と同じ。
- D
正しい。
labelを付けた線が 2 本あるので、凡例の項目は 2 つ。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。