Add seaborn.palplot axes to existing figure for visualisation of different color palettes

2024/10/11 6:37:06

Adding seaborn figures to subplots is usually done by passing 'ax' when creating the figure. For instance:

sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=ax)

This method, however, doesn't apply to seaborn.palplot, which visualizes seaborn color palettes. My goal is to create a figure of different color palettes for scalable color comparison and presentation. This image roughly shows the figure I'm trying to create [source].

A possibly related answer describes a method of creating a seaborn figure and copying the axes to another figure. I haven't been able to apply this method to the palplot figures, and would like to know if there is a quick way to force them into the existing figure.

Here's my minimum working example, now still generating separate figures.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as pltfig1 = plt.figure()
length, n_colors = 12, 50  # amount of subplots and colors per subplot
start_colors = np.linspace(0, 3, length)
for i, start_color in enumerate(start_colors):ax = fig1.add_subplot(length, 1, i + 1)colors = sns.cubehelix_palette(n_colors=n_colors, start=start_color,rot=0, light=0.4, dark=0.8)sns.palplot(colors)
plt.show(fig1)

Ultimately, to make the plot more informative, it would be great to print the RGB values stored in colors (list-like) evenly spaced over the palplots, but I don't know if this is easily implemented due to the unusual way of plotting in palplot.

Any help would be greatly appreciated!

Answer

As you've probably already found, there's little documentation for the palplot function, but I've lifted directly from the seaborn github repo here:

def palplot(pal, size=1):"""Plot the values in a color palette as a horizontal array.Parameters----------pal : sequence of matplotlib colorscolors, i.e. as returned by seaborn.color_palette()size :scaling factor for size of plot"""n = len(pal)f, ax = plt.subplots(1, 1, figsize=(n * size, size))ax.imshow(np.arange(n).reshape(1, n),cmap=mpl.colors.ListedColormap(list(pal)),interpolation="nearest", aspect="auto")ax.set_xticks(np.arange(n) - .5)ax.set_yticks([-.5, .5])# Ensure nice border between colorsax.set_xticklabels(["" for _ in range(n)])# The proper way to set no ticksax.yaxis.set_major_locator(ticker.NullLocator())

So, it doesn't return any axes or figure objects, or allow you to specify an axes object to write into. You could make your own, as follows, by adding the ax argument and a conditional in case it's not provided. Depending on context, you may need the included imports as well.

def my_palplot(pal, size=1, ax=None):"""Plot the values in a color palette as a horizontal array.Parameters----------pal : sequence of matplotlib colorscolors, i.e. as returned by seaborn.color_palette()size :scaling factor for size of plotax :an existing axes to use"""import numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltimport matplotlib.ticker as tickern = len(pal)if ax is None:f, ax = plt.subplots(1, 1, figsize=(n * size, size))ax.imshow(np.arange(n).reshape(1, n),cmap=mpl.colors.ListedColormap(list(pal)),interpolation="nearest", aspect="auto")ax.set_xticks(np.arange(n) - .5)ax.set_yticks([-.5, .5])# Ensure nice border between colorsax.set_xticklabels(["" for _ in range(n)])# The proper way to set no ticksax.yaxis.set_major_locator(ticker.NullLocator())

This function should work like you expect when you include the 'ax' argument. To implement this in your example:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as pltfig1 = plt.figure()
length, n_colors = 12, 50  # amount of subplots and colors per subplot
start_colors = np.linspace(0, 3, length)
for i, start_color in enumerate(start_colors):ax = fig1.add_subplot(length, 1, i + 1)colors = sns.cubehelix_palette(n_colors=n_colors, start=start_color, rot=0, light=0.4, dark=0.8)my_palplot(colors, ax=ax)
plt.show(fig1)

example results

https://en.xdnf.cn/q/69803.html

Related Q&A

Running Django with Run can not find LESS CSS

I have a Django project that uses buildout. When running or debugging the application it runs fine by using my buildout script. I also use django-compressor to compress and compile my LESS files. I ins…

OpenCV + python -- grab frames from a video file

I cant seem to capture frames from a file using OpenCV -- Ive compiled from source on Ubuntu with all the necessary prereqs according to: http://opencv.willowgarage.com/wiki/InstallGuide%20%3A%20Debia…

python 3.1 - Creating normal distribution

I have scipy and numpy, Python v3.1I need to create a 1D array of length 3million, using random numbers between (and including) 100-60,000. It has to fit a normal distribution. Using a = numpy.random.…

Faster way to iterate all keys and values in redis db

I have a db with about 350,000 keys. Currently my code just loops through all keys and gets its value from the db.However this takes almost 2 minutes to do, which seems really slow, redis-benchmark gav…

How to store a floating point number as text without losing precision?

Like the question says. Converting to / from the (truncated) string representations can affect their precision. But storing them in other formats like pickle makes them unreadable (yes, I want this too…

Integer in python/pandas becomes BLOB (binary) in sqlite

Storing an integer in sqlite results in BLOBs (binary values) instead of INTEGER in sqlite. The problem is the INT in the "Baujahr" column. The table is created. CREATE TABLE "Objekt&quo…

Calling Scrapy Spider from Django

I have a project with a django and scrapy folder in the same workspace:my_project/django_project/django_project/settings.pyapp1/app2/manage.py...scrapy_project/scrapy_project/settings.pyscrapy.cfg...Iv…

Python Threading: Multiple While True loops

Do you guys have any recommendations on what python modules to use for the following application: I would like to create a daemon which runs 2 threads, both with while True: loops. Any examples would b…

Visual Studio Code - input function in Python

I am trying out Visual Studio Code, to learn Python.I am writing a starter piece of code to just take an input from the user, say:S = input("Whats your name? ")When I try to run this (Mac: C…

DRF: how to change the value of the model fields before saving to the database

If I need to change some field values before saving to the database as I think models method clear() is suitable. But I cant call him despite all my efforts.For example fields email I need set to lowe…