简体   繁体   中英

How do I find color limits for qualitative colormaps in Matplotlib?

I have a following code that generates a scatter plot:

plt.scatter(df['column_A'], y= df['column_B'], 
            alpha = .6, c = df['column_C'], cmap = 'Accent')

It generates this chart where points are colored based on values from 'column_C'

I am using qualitative colormap in cmap which automatically creates intervals on column_C and color the points accordingly. I can visually say that the grey group ranges from around 10 to the maximum in data (around 12) but I would like to access the exact numbers. Is there a way to do that?

Thanks a lot

By default, the colors range from the smallest to the largest values of column_C . For the colormap with N colors, there will be N segments, thus N+1 borders which can be calculated with np.linspace() .

Here is some illustrating code. Both a colorbar with default ticks and one with ticks at the color borders are added.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'column_A': np.random.rand(100),
                   'column_B': np.random.rand(100),
                   'column_C': np.random.rand(100) * 20 - 8})
cmap = plt.get_cmap('Accent')
plt.scatter(df['column_A'], y=df['column_B'],
            alpha=.6, c=df['column_C'], cmap=cmap)
plt.colorbar()  # the default color bar
color_borders = np.linspace(df['column_C'].min(), df['column_C'].max(), cmap.N + 1)
plt.colorbar(ticks=color_borders)  # ticks at the color borders
plt.show()

在颜色栏中查找颜色边框

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM