LoginSignup
0
2

More than 3 years have passed since last update.

[Python] Altairの凡例(legend)をプロットエリア内に表示させる

Posted at

How To Place Legend Inside the Plot area in Altair

この記事について

最近はpandas/dataframeと相性がいいAltairが気にいって使っています。
しかし、凡例の位置はmatplotlibだとプロット内に表示されるのに、Altairだと外になってしまい、位置の調節の仕方が分かりませんでした。英語でもなかなか資料が見つからなかったのですが、AltairがパースしているVega-Liteのドキュメントなどをみて解決しましたので、記事にします。

非常に参考にさせていただいた、こちらのサイトよりIrisのデータのグラフにて説明したいと思います。
Altairのすすめ!Pythonによるデータの可視化

BEFORE  デフォルトでは右側に出てしまいます
スクリーンショット 2021-01-19 100349.png

import altair as alt
from vega_datasets import data
iris = data.iris()

alt.Chart(iris).mark_point().encode(
    alt.X("sepalLength", scale=alt.Scale(zero=False)),
    alt.Y("sepalWidth", scale=alt.Scale(zero=False)),
    color="species"
).interactive()

AFTER   plot areaの任意の場所に移せます
スクリーンショット 2021-01-19 101032.png


import altair as alt
from vega_datasets import data
iris = data.iris()

alt.Chart(iris).mark_point().encode(
    alt.X("sepalLength", scale=alt.Scale(zero=False)),
    alt.Y("sepalWidth", scale=alt.Scale(zero=False)),
    color=alt.Color("species", 
        legend=alt.Legend(orient='none', legendX=250, legendY=5,  ## orientをnoneに設定するとlegenX,legendYが指定できる
                strokeColor='blue', fillColor='white', padding=10)) ## legendの四角の設定
)

凡例設定のポイント

コードをみていただければ分かるかと思いますが、alt.Legendでいろいろと細かく調整できます。
LegendXとLegendYで位置を調整できますが、その際にoriend='none'としておくのがポイントです。なお、このxとyの数値は何なのか、ちょっと分かりません・・なんとなくできてしまいますが、誰かご存知でしたら教えてください

以下、参考にしたVeg-Liteのdocumentの大事なところをスクショして載せます。
Legend | Vega-Lite
https://vega.github.io/vega-lite/docs/legend.html

スクリーンショット 2021-01-19 103539.png
スクリーンショット 2021-01-19 103610.png
スクリーンショット 2021-01-19 103720.png


こちらの記事とは関係ありませんが、この中国の方のサイトの例は充実していました。
Python Altair COVID-19疫情数据可视化实践经验分享
https://www.cnblogs.com/dotlink/archive/2004/01/13/covid-19.html

0
2
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
0
2