Customizing the Legend#
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
df = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv")
print(df.shape)
df.head()
(234, 12)
| Unnamed: 0 | manufacturer | model | displ | year | cyl | trans | drv | cty | hwy | fl | class | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | audi | a4 | 1.8 | 1999 | 4 | auto(l5) | f | 18 | 29 | p | compact |
| 1 | 2 | audi | a4 | 1.8 | 1999 | 4 | manual(m5) | f | 21 | 29 | p | compact |
| 2 | 3 | audi | a4 | 2.0 | 2008 | 4 | manual(m6) | f | 20 | 31 | p | compact |
| 3 | 4 | audi | a4 | 2.0 | 2008 | 4 | auto(av) | f | 21 | 30 | p | compact |
| 4 | 5 | audi | a4 | 2.8 | 1999 | 6 | auto(l5) | f | 16 | 26 | p | compact |
Guides#
guide_legend()#
# Default categorical legend
p2 = ggplot(df, aes("displ", "hwy", color="class")) + geom_point(size=5)
p2
# Legend name
p2 + scale_color_discrete(guide=guide_legend("Vehicle class"))
# Layout the legend in two columns
p2 + scale_color_discrete(guide=guide_legend(ncol=2))
# Fill by rows
p2 + scale_color_discrete(guide=guide_legend(ncol=2, byrow=True))
guide_colorbar()#
# Default color legend
p3 = ggplot(df, aes("displ", "hwy")) + geom_point(aes(color="cty"))
p3
# Legend name
p3 + scale_color_continuous(guide=guide_colorbar("City mileage"))
# Adjust colorbar size
p3 + scale_color_continuous(guide=guide_colorbar(barwidth=10, barheight=200))
# Fewer bins
p3 + scale_color_continuous(breaks=[13, 22, 31], guide=guide_colorbar(nbin=3))
guides()#
# Default complex legend
p4 = ggplot(df, aes("displ", "hwy")) + geom_point(aes(color="cty", shape="drv"), size=5)
p4
# Guides for 'color' and 'shape' aesthetics
p4 + guides(color=guide_colorbar(barwidth=10), shape=guide_legend(ncol=2))
Customizing Aesthetics Appearance with override_aes#
p4 + guides(shape=guide_legend(override_aes={'size': 8, 'color': "#f03b20"}))