import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
# Load MPG dataset
mpg = pd.read_csv ("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv")
mpg.head ()
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 |
# Default legend
p = ggplot(mpg, aes('displ', 'hwy', color='manufacturer')) + geom_point(size=5) + ggsize(500,250)
p
# Layout the legend in two columns
p + scale_color_discrete(guide=guide_legend(ncol=2)) + ggtitle('Two columns legend')
# Same and fill by rows
p + scale_color_discrete(guide=guide_legend(ncol=2, byrow=True)) \
+ ggtitle('Two columns legend filled by rows')
# Adjust legend and axis
# - five rows legend
# - draw legend below
# - remove axis
p + scale_color_discrete(guide=guide_legend(nrow=5)) \
+ theme_minimal() + theme(legend_position='bottom') \
+ ggtitle('Five rows legend and below') \
+ ggsize(500,400)
# Set color to city MPG and shape to driveĀ·train
p1 = ggplot(mpg, aes(x='displ', y='hwy')) + geom_point(aes(color='cty', shape='drv'), size=5) + ggsize(700, 350)
p1
# Change legend position and orientation
p1 + theme(legend_position=[1, 1], legend_justification=[1, 1], legend_direction='horizontal')
# Adjust colorbar size
# Change order in drive-train legend
# Set labels to legends and axis
# Remove vertical axis line
p1 + theme(legend_position=[1, 1], legend_justification=[1, 1], legend_direction='horizontal') \
+ scale_color_continuous(name='City MPG', low='dark_blue', high='light_blue', guide=guide_colorbar(barheight=10, barwidth=300)) \
+ scale_shape(name='Drive-train', breaks=['f', 'r', '4'], labels=['front', 'rear', '4X4']) \
+ xlab('Engine displacement (L)') + ylab('Highway MPG')