How To Place Legend Inside the Plot area in Altair
Recently, I like Altair, which is compatible with pandas/dataframe. However, the position of the legend is displayed in the plot with matplotlib, but it is outside with Altair, so I did not know how to adjust the position. I couldn't find the material in English, but I solved it by looking at the Vega-Lite document parsed by Altair, so I will write it as an article.
I would like to explain with a graph of Iris data from this site, which was very helpful. [Recommendation of Altair! Data visualization with Python] (https://qiita.com/dr666m1/items/b71bef31ba3a21868095)
BEFORE By default, it will appear on the right side
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 can be moved to any location in the plot area
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, ##If orient is set to none, legendX,legendY can be specified
strokeColor='blue', fillColor='white', padding=10)) ##Legend square setting
)
As you can see from the code, you can make various fine adjustments with alt.Legend. You can adjust the position with LegendX and LegendY, but the point is to set oriend ='none' at that time. In addition, I do not know what the numerical values of x and y are ... I can do it somehow, but if anyone knows, please let me know.
Below, I will take a screenshot of the important parts of the Veg-Lite document that I referred to. Legend | Vega-Lite https://vega.github.io/vega-lite/docs/legend.html
Although it has nothing to do with this article, the examples of this Chinese site were substantial. Python Altair COVID-19 Epidemic Number Visualization Practice Economic Experience https://www.cnblogs.com/dotlink/archive/2004/01/13/covid-19.html
Recommended Posts