- How to Get a List of N Different Colors and Names in Python/Pandas
- Step 1: Generate N Random Colors with Python
- Step 2: Display N random colors with Python and JupyterLab
- Step 3: Get color palette with seaborn and Python
- Step 4: Get color palette with matplotlib
- Step 5: Working with color names and color values format (HTML and CSS) in Python
- Array of colors in python
- Array of colors in python
- Result Example:
- Array of Colors in Windows8 or wpf?
- C# getting all colors from Color
- Array of Index to colors to array of colors in python [duplicate]
How to Get a List of N Different Colors and Names in Python/Pandas
Looking to generate a list of different colors or get color names in Python? We are going to demonstrate combination of different modules like:
In order to generate, list color names and values. Also we can see how to work with color palettes and HTML/CSS values.
If so, you’ll see the options to accomplish these goals using simple examples.
Step 1: Generate N Random Colors with Python
In this step we will get a list of many different colors as hex values in Python. We are going to use pure Python code and will generate a list of unique colors with randomint and for loop:
from random import randint color = [] n = 10 for i in range(n): color.append('#%06X' % randint(0, 0xFFFFFF))
This will generate a list like:
[‘#4E8CA1’, ‘#F9C1E7’, ‘#933D05’, ‘#595697’, ‘#417D22’, ‘#7D8377’, ‘#624F7B’, ‘#C25D39’, ‘#A24AFD’, ‘#2AED9E’]
You need to provide just the number of the random colors to be generated.
Step 2: Display N random colors with Python and JupyterLab
To display the different colors generated from the above code we are going to use Pandas.
First we are going to define a function which is going to display each row of a Pandas DataFrame in a different color(more example on formatting — How to Set Pandas DataFrame Background Color Based On Condition) :
from random import randint def format_color_groups(df, color): x = df.copy() i = 0 for factor in color: style = f'background-color: ' x.loc[i] = style i = i + 1 return x
Next we are going to generate a DataFrame with a random integers (more info — How to Create a Pandas DataFrame of Random Integers:
from random import randint import numpy as np import pandas as pd color = [] n = 10 df = pd.DataFrame(np.random.randint(0,n,size=(n, 2)), columns=list('AB'))
Finally we are going to apply the function to the generated DataFrame and pass the list of colors:
df.style.apply(format_color_groups, color=color, axis=None)
A | B | |
---|---|---|
0 | 4 | 4 |
1 | 3 | 4 |
2 | 5 | 0 |
3 | 5 | 1 |
4 | 8 | 2 |
5 | 7 | 4 |
6 | 3 | 2 |
7 | 5 | 0 |
8 | 2 | 1 |
9 | 8 | 9 |
Step 3: Get color palette with seaborn and Python
Python package seaborn offers color palettes with different styles. You can find more about it: seaborn.color_palette
Below you can find a simple example:
import seaborn as sns sns.color_palette()
sns.color_palette("flare") sns.color_palette("pastel")
You can find the generated colors on the image below:
How many colors to generate depends on a parameter:
palette = sns.color_palette(None, 3)
Step 4: Get color palette with matplotlib
Another option to get different color palettes in Python is with the package matplotlib. After installing it you can generate different color ranges with code like:
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import cm from collections import OrderedDict cmaps = OrderedDict() cmaps['Miscellaneous'] = [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral', 'gist_ncar'] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list): # Create figure and adjust figure height to number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh)) fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(cmap_category + ' colormaps', fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10, transform=ax.transAxes) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axs: ax.set_axis_off() for cmap_category, cmap_list in cmaps.items(): plot_color_gradients(cmap_category, cmap_list) plt.show()
Step 5: Working with color names and color values format (HTML and CSS) in Python
Additional library webcolors is available if you need to:
- get the color name in Python
- convert color name to HTML/CSS or hex format
More about this Python module: webcolors.
And example usage of converting hex value to color name:
import webcolors webcolors.hex_to_name(u'#daa520') webcolors.hex_to_name(u'#000000') webcolors.hex_to_name(u'#FFFFFF')
On the other hand if you like to get the color value based on its name you can do:
webcolors.html5_parse_legacy_color(u'lime') webcolors.html5_parse_legacy_color(u'salmon')
By using DataScientYst — Data Science Simplified, you agree to our Cookie Policy.
Array of colors in python
Solution 4: This is what I think you want: it will loop through all the standard values for color, and should work for what you need Question: Having an array (2d) with index of colors is there a way to replace the index by its color in one step not element by element? Solution 1: You could take color from KnownColor or use reflection to avoid color like Menu , Desktop. contain in KnowColor Solution 2: Similar to @madgnome’s code, but I prefer the following since it doesn’t require parsing the string names (a redundant indirection, in my opinion): Solution 3: My way to get colors.
Array of colors in python
What’s the quickest way to get an Array of colors in python ? Something I can index and pass to as the «color=» argument plotting in pylab.
The best I can come up with is:
colors = [(random(),random(),random()) for i in range(10)]
but a solution that can generate well-spaced colors (interpolated?) would be preferable.
from random import randint colors = [] for i in range(10): colors.append('#%06X' % randint(0, 0xFFFFFF))
Result Example:
[‘#37AB65’, ‘#3DF735’, ‘#AD6D70’, ‘#EC2504’, ‘#8C0B90’, ‘#C0E4FF’, ‘#27B502’, ‘#7C60A8’, ‘#CF95D7’, ‘#145JKH’]It seems like matplotlib comes with several builtin «colormaps». You can get one using get_cmap ().
You can simply make a list or a dictionary and add the colors to it, I don’t know how pylab works but I found an example which might work for you here.
from pylab import * cdict = my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256) pcolor(rand(10,10),cmap=my_cmap) colorbar()
Array of colors in python, What’s the quickest way to get an array of colors in python? Something I can index and pass to as the «color=» argument plotting in pylab. The …
Array of Colors in Windows8 or wpf?
I was trying to import my WP7 proj to Windows 8. I have an array of
How do I do the same in WPF?
Have you added the appropriate namespaces to your code?
should sort out the issues.
Following from the comments that you tried this, and it «didn’t work», I put together this page in VS. The .cs file is as below, and all compiles fine.
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace MyNamespace < public partial class ColorTestPage : Window < public ColorTestPage() < InitializeComponent(); Color[] g_colors = < Colors.Yellow, Colors.Blue, Colors.Brown, Colors.Cyan, Colors.DarkGray, Colors.Gray, Colors.Green, Colors.LightGray, Colors.Magenta, Colors.Orange,Colors.Purple,Colors.Red,Colors.White >; > > >
Tikz pgf — How to create an array of colors?, I am trying to pass an array of colors (of any length) into a macro command to then be used when filling the background of tikz shapes. I’ve been …
C# getting all colors from Color
I want to make a ComboBox filled with all the colors from System.Drawing.Color
But I can’t seem to collect all the colors from that collection
I’ve already tried using a foreach to do the job like this:
foreach (Color clr in Color)
But all I get is an error.
So how can I loop trough all the colors?
Any help will be appreciated.
You could take color from KnownColor
KnownColor[] colors = Enum.GetValues(typeof(KnownColor)); foreach(KnownColor knowColor in colors)
or use reflection to avoid color like Menu , Desktop. contain in KnowColor
Type colorType = typeof(System.Drawing.Color); // We take only static property to avoid properties like Name, IsSystemColor . PropertyInfo[] propInfos = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (PropertyInfo propInfo in propInfos)
Similar to @madgnome’s code, but I prefer the following since it doesn’t require parsing the string names (a redundant indirection, in my opinion):
foreach (var colorValue in Enum.GetValues(typeof(KnownColor))) Color color = Color.FromKnownColor((KnownColor)colorValue);
My way to get colors. I think it is the best way via Reflection library.
private List GetAllColors() < ListallColors = new List(); foreach (PropertyInfo property in typeof(Color).GetProperties()) < if (property.PropertyType == typeof(Color)) < allColors.Add((Color)property.GetValue(null)); >> return allColors; >
This is what I think you want:
foreach (Color color in new ColorConverter().GetStandardValues())
it will loop through all the standard values for color, and should work for what you need
JavaScript color Array, This program produces a random background color by pressing a button. The colors are «X11 colors» from the CSS3 specification WebColors. I …
Array of Index to colors to array of colors in python [duplicate]
Having an array (2d) with index of colors is there a way to replace the index by its color in one step not element by element?
colors=[[255,0,0],[125,222,11]] im_x=[[0,0],[1,0]] #the result must be: im_c= [[[255,0,0],[255,0,0]],[[125,222,11],[255,0,0]]
I have try colors[im_x] but it does not work 🙁
Define the arrays as numpy arrays, and then index them as you were trying to:
import numpy as np colors = np.array([[255,0,0],[125,222,11]]) im_x = np.array([[0,0],[1,0]]) colors[im_x] array([[[255, 0, 0], [255, 0, 0]], [[125, 222, 11], [255, 0, 0]]])
How do I color an image using an array of selected, I have an image that I am trying to set a random color. public Color teamAColor; public void Start() < teamAColor = new Color (0, 1, 0, 1); Image …