Customizing Colors
If you don’t like the colors chosen by Altair for your scatter plot, you can customize the colors. The default colors can be changed using the scale argument of the Color class, By passing the Scale class to the scale argument. The available customizations are:
- Custom mapping of colors to discrete values: For custom mapping, we use domain and range parameters of the Scale and pass list for values and colors resp.
- Color Schemes: There are many color schemes given by the Vega project. If you like dark colors, you can use the ‘dark2’ scheme and if there are more than 10 categories you can use the ‘category20’ scheme.
Example 1: Custom mapping of colors to discrete values:
Python3
# Python3 program to illustrate # How to do custom mapping # of colors to discrete values # for scatter plot coloring # using altair # Importing altair and vega_datasets library import altair as alt from vega_datasets import data # Selecting the cars dataset cars = data.cars() # Making two lists for # values and colors resp. dom = [ 'Europe' , 'Japan' , 'USA' ] rng = [ 'red' , 'green' , 'black' ] # Making the Scatter Plot alt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x = 'Miles_per_Gallon' , # Map the Horsepower to y-axis y = 'Horsepower' , # Coloring the Scatter Plot # using Origin variable and # custom colors color = alt.Color( 'Origin' , scale = alt. Scale(domain = dom, range = rng)) ) |
Output:
Example 2(Color Schemes):
Python3
# Python3 program to illustrate # How to select color schemes # for scatter plot coloring # using altair # Importing altair and vega_datasets library import altair as alt from vega_datasets import data # Selecting the cars dataset cars = data.cars() # Making the Scatter Plot alt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x = 'Miles_per_Gallon' , # Map the Horsepower to y-axis y = 'Horsepower' , # Coloring the Scatter Plot # using Origin variable and # color scheme color = alt.Color( 'Origin' , scale = alt. Scale(scheme = 'dark2' )) ) |
Output:
How To Color a Scatter Plot by a Variable in Altair?
Altair is a simple and easy to use statistical visualization library for python. It provides many types of visualizations ranging from simple bar charts to compound visualizations like box plots. Scatter Plot is one of the most useful visualizations in the Altair library for bivariate analysis and finding relationships between two data columns in a data set.