Home > OS >  Is there a way to use two colormaps in a pyplot scatterplot?
Is there a way to use two colormaps in a pyplot scatterplot?

Time:07-29

I've got a spatial dataset that I'm plotting with a scatterplot, and I'm wondering if there is a way to use two colormaps for the data depending on a categorical variable? Basically I want to colorize a functional relationship by latitude, but I also want to identify landcover as part of the visualization.

Landcover in my case would be a binary indicator, and the colormap indicates the latitude that a point occurs at. Making this more clear, I have

  • A response variable Y
  • A predictor variable X
  • The latitude where each point (X, Y) occurs at (which is what I want to colorize)
  • A binary indicator for landcover that I want to incorporate in the visualization

The code I have now is

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# generating sample data as an example
x = np.random.normal(size = 192 * 50)
y = np.random.normal(size = 192 * 50)
lat = np.tile(np.linspace(-90, 90, 192), 50)
landcover = np.random.choice([0, 1], size = 192 * 50, replace = True)

# create a colorbar
cmap = sns.dark_palette("#69d", reverse = True, as_cmap = True)

plt.figure(figsize = (10, 8))
plt.scatter(x, y, c = lat, alpha = 0.2, cmap = cmap)
cbar = plt.colorbar()
cbar.solids.set(alpha = 1) # to counter the transparency in the plot
plt.grid(alpha = 0.2)
plt.show()

enter image description here

I'm not sure how to approach modifying this code to add the landcover information. I envisioned adding another colorbar to the right of the current one and just plotting subsets of the data based on the indicator variable. And I know how to do every step except adding the second colorbar as described. Has anyone ever solved an equivalent problem?

CodePudding user response:

Yes you can. To achieve it, you will use plt.scatter twice for each dataset and change the colormap there. With respect to the colorbar, that's trickier. Use the following code

import matplotlib.colors as colors
import matplotlib.cm as cm

plt.colorbar(mappable=cm.ScalarMappable(norm=colors.Normalize(vmin=0, vmax=1, clip=False),\
            cmap=plt.get_cmap("BrBG")), location='left')
plt.colorbar(mappable=cm.ScalarMappable(norm=colors.Normalize(vmin=0, vmax=1, clip=False),\
            cmap=plt.get_cmap("BrBG")), location='right')

Don't forget to change cmap to the one yout dataset uses and also change the boundaries if needed. You may also need to refer to your axes but I am not so sure of that. However, this should work

  • Related