Course Content
Visualization in Python with matplotlib
Visualization in Python with matplotlib
Further Grouping
In the previous chapter, we colored the points in accordance with the continent. This was the categorical variable (which means it can take on one of a limited, usually fixed, number of possible values). But what if we want to use colors in accordance with a numeric variable? In that case, most likely, we are talking about the continuous variable (can take on an uncountable set of values). A popular solution is using colormaps (I assume you heard about heatmaps). With this approach, points are colored more intense the color is, the greater value (for example).
Let's return to our traditional example. To use colormap we need to follow the next steps:
- Assign
ax.scatter()
to some variable, and additionally passcmap
as a parameter (this one is colormap; possible values are in the documentation); - Apply the
.colorbar
function to theFigure
object (usuallyfig
), passing the newly created variable (step 1) as a parameter.
# Import the libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # Reading the data data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/gapminder2017.csv', index_col = 0) # Create Figure and Axes objects fig, ax = plt.subplots() # Initialize a scatter plot and colorbar cax = ax.scatter(data['gdp per capita'], data['internet users'], c = data['life exp'], cmap = 'cividis') fig.colorbar(cax) # Display the plot plt.show()
Thanks for your feedback!