I'm trying to plot a numpy array with shape [height x width x 3] containing RGB values. As a simple example suppose you have the Belgian flag:
import numpy as np
import matplotlib.pyplot as plt
flag = np.empty((1,3,3))
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254,240,71)
flag[0,2,:] = (255,55,14)
plt.imshow(flag)
plt.show()
This results in the following output:
Can anyone tell me why it is not plotting the right RGB values? Did I make a mistake in the dimensionality? Probably an easy answer to this, but can't seem to find it .. Thanks a lot for any advice!
The default data type for the array created by numpy.empty is floating point, and imshow treats floating point values differently than integer values. (imshow expects floating point values to be in the range 0.0 to 1.0.)
Change this
flag = np.empty((1,3,3))
to
flag = np.empty((1,3,3), dtype=np.uint8)
The reason you got those particular colors when flag is floating point is that imshow apparently converted your array to integer without checking that the input values were in the range 0.0 to 1.0. Here's what happens in that case:
In [25]: flag
Out[25]:
array([[[ 0., 0., 0.],
[ 254., 240., 71.],
[ 255., 55., 14.]]])
In [26]: img = (flag*255).astype(np.uint8)
In [27]: img
Out[27]:
array([[[ 0, 0, 0],
[ 2, 16, 185],
[ 1, 201, 242]]], dtype=uint8)
If you then run imshow(img), you get the black, blue and cyan plot.
Try to use the float values between 0 ~ 1.
So change the code like this,
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254/255,240/255,71/255)
flag[0,2,:] = (255/255,55/255,14/255)
Related
I was working on the code "Discrete distribution as horizontal bar chart", found here LINK, using Matplotlib 3.1.1
I've been circling around the question for a while, but I still can't figure it out: what's the meaning of the instruction: category_colors = plt.get_cmap('RdYlGn')(np.linspace(0.15, 0.85, data.shape[1])) ?
As np.linspace(0.15, 0.85, data.shape[1]) resolves to array([0.15 , 0.325, 0.5 , 0.675, 0.85 ]), I first thought that the program was using the colormap RdYlGn (supposed to go from color=0.0 to color=1.0) and was then taking the 5 specific colors located at point 0.15, etc., 0.85
But, printing category_colors resolves to a (5, 4) array:
array([[0.89888504, 0.30549789, 0.20676663, 1. ],
[0.99315648, 0.73233372, 0.42237601, 1. ],
[0.99707805, 0.9987697 , 0.74502115, 1. ],
[0.70196078, 0.87297193, 0.44867359, 1. ],
[0.24805844, 0.66720492, 0.3502499 , 1. ]])
I don't understand what these numbers refer to ???
plt.get_cmap('RdYlGn') returns a function which maps a number between 0 and 1 to a corresponding color, where 0 gets mapped to red, 0.5 to yellow and 1 to green. Often, this function gets the name cmap = plt.get_cmap('RdYlGn'). Then cmap(0) (which is the same as plt.get_cmap('RdYlGn')(0)) would be the rbga-value (0.6470588235294118, 0.0, 0.14901960784313725, 1.0) for (red, green, blue, alpha). In hexadecimal, this color would be #a50026.
By numpy's broadcasting magic, cmap(np.array([0.15 , 0.325, 0.5 , 0.675, 0.85 ])) gets the same result as np.array([cmap(0.15), cmap(0.325), ..., cmap(0.85)]). (In other words, many numpy functions applied to an array return an array of that function applied to the individual elements.)
So, the first row of category_colors = cmap(np.linspace(0.15, 0.85, 5)) will be the rgba-values of the color corresponding to value 0.15, or 0.89888504, 0.30549789, 0.20676663, 1.. This is a color with 90% red, 31% green and 21% blue (and alpha=1 for complete opaque), so quite reddish. The next row are the rgba values corresponding to 0.325, and so on.
Here is some code to illustrate the concepts:
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex # convert a color to hexadecimal format
from matplotlib.cm import ScalarMappable # needed to create a custom colorbar
import numpy as np
cmap = plt.get_cmap('RdYlGn')
color_values = np.linspace(0.15, 0.85, 5)
category_colors = cmap(color_values)
plt.barh(color_values, 1, height=0.15, color=category_colors)
plt.yticks(color_values)
plt.colorbar(ScalarMappable(cmap=cmap), ticks=color_values)
plt.ylim(0, 1)
plt.xlim(0, 1.1)
plt.xticks([])
for val, color in zip(color_values, category_colors):
r, g, b, a = color
plt.text(0.1, val, f'r:{r:0.2f} g:{g:0.2f} b:{b:0.2f} a:{a:0.1f}\nhex:{to_hex(color)}', va='center')
plt.show()
PS: You might also want to read about norms, which map an arbitrary range to the range 0,1 to be used by colormaps.
I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I've got very close with this:
plt.scatter(w, M, c=p, marker='s')
where w and M are the data points and p is the variable I want to shade with respect to.
However I want to do it in greyscale rather than colour. Can anyone help?
There's no need to manually set the colors. Instead, specify a grayscale colormap...
import numpy as np
import matplotlib.pyplot as plt
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
# Plot...
plt.scatter(x, y, c=y, s=500) # s is a size of marker
plt.gray()
plt.show()
Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,
Plot points corresponding to Physical variable 'A' in RED.
Plot points corresponding to Physical variable 'B' in BLUE.
Plot points corresponding to Physical variable 'C' in GREEN.
In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.
x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]
# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
cols=[]
for l in lst:
if l=='A':
cols.append('red')
elif l=='B':
cols.append('blue')
else:
cols.append('green')
return cols
# Create the colors list using the function above
cols=pltcolor(x)
plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()
I have a plot of values sampled from the set [ -1, 0, 1] and each value is mapped to a color. However it is possible to have a sample where only two different values appear ( [-1,0], [-1,1], [0,1] ) and if that happens, then the color scheme should adapt accordingly
If the number of unique values is 3, then this code works
ax2 = plt.subplot2grid((n_rows , 1), (2, 0))
colors = [(216/255, 24/255, 24/255), (1, 1, 1), (143/255, 188/255, 143/255)]
positions = df['long'].astype(int) - df['short'].astype(int)
cm = LinearSegmentedColormap.from_list('mycols', colors, N=3)
ax2.pcolorfast(ax2.get_xlim(), ax2.get_ylim(), positions.values[np.newaxis], cmap=cm, alpha=0.5)
The result is
How should I manage the scenarios where only two colors are needed?
I think this controls the number of segments, but I don't know how to account for the color scheme
cm = LinearSegmentedColormap.from_list('colores', colors, N=len(list(set(positions))))
If you make colors a numpy array, you could do something along these lines: colors[np.isin([-1, 0, 1], sorted(available_values))] to select just the wanted colours. The [-1, 0, 1] should of course be a complete list of all available values, with a one to one correspondence with colors.
Note that this may not work when the values are floating point values, since the comparison will not be accurate at times.
Example code (untested):
all_values = np.array([-1, 0, 1])
colors = np.array([(216/255, 24/255, 24/255), (1, 1, 1), (143/255, 188/255, 143/255)])
positions = df['long'].astype(int) - df['short'].astype(int)
available_values = set(positions)
cm = LinearSegmentedColormap.from_list('mycols', colors[np.isin(all_values, sorted(available_values))], N=len(available_values))
ax2.pcolorfast(ax2.get_xlim(), ax2.get_ylim(), positions.values[np.newaxis], cmap=cm, alpha=0.5)
Usually one would not create new colormap for each plot with different values, but rather change the normalization.
Here, as I understand it, there are only ever the values [-1,0,1] or any subset of those in use. Hence one may use a single normalization as plt.Normalize(-1,1) throughout.
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
colors = [(216/255., 24/255., 24/255.), (1., 1., 1.), (143/255., 188/255., 143/255.)]
cmap = ListedColormap(colors)
norm=plt.Normalize(-1,1)
combinations = [[-1,0,1],[-1,0],[0,1],[-1,1]]
fig, axes = plt.subplots(nrows=len(combinations), sharex=True)
for combo, ax in zip(combinations, axes):
data = np.random.choice(combo, size=(50))
ax.pcolorfast(np.atleast_2d(data), cmap=cmap, norm=norm, alpha=0.5)
ax.set_ylabel(combo)
plt.show()
For the pyplot.scatter(x,y,s,c....) function ,
The matplotlib docs states that :
c : color, sequence, or sequence of color, optional, default: 'b' The
marker color. Possible values:
A single color format string. A sequence of color specifications of
length n. A sequence of n numbers to be mapped to colors using cmap
and norm. A 2-D array in which the rows are RGB or RGBA. Note that c
should not be a single numeric RGB or RGBA sequence because that is
indistinguishable from an array of values to be colormapped. If you
want to specify the same RGB or RGBA value for all points, use a 2-D
array with a single row.
However i do not understand how i can change the colors of the datapoints as i wish .
I have this piece of code :
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib
%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (13.0, 9.0)
# Generate a dataset and plot it
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.55)
print(y)
plt.scatter(X[:,0], X[:,1], c=y)#, cmap=plt.cm.Spectral)
the output plot
How can i change the colours to suppose black and green datapoints if i wish ? or something else ? Also please explain what exactly cmap does .
Why my plots are magenta and blue every time i use plt.cm.Spectral ?
There are essentially two option on how to colorize scatter points.
1. External mapping
You may externally map values to color and supply a list/array of those colors to the scatter's c argument.
z = np.array([1,0,1,0,1])
colors = np.array(["black", "green"])
plt.scatter(x,y, c=colors[z])
2. Internal mapping
Apart from explicit colors, one can also supply a list/array of values which should be mapped to colors according to a normalization and a colormap.
A colormap is a callable that takes float values between 0. and 1. as input and returns a RGB color.
A normalization is a callable that takes any number as input and outputs another number, based on some previously set limits. The usual case of Normalize would provide a linear mapping of values between vmin and vmax to the range between 0. and 1..
The natural way to obtain a color from some data is hence to chain the two,
cmap = plt.cm.Spectral
norm = plt.Normalize(vmin=4, vmax=5)
z = np.array([4,4,5,4,5])
plt.scatter(x,y, c = cmap(norm(z)))
Here the value of 4 would be mapped to 0 by the normalzation, and the value of 5 be mapped to 1, such that the colormap provides the two outmost colors.
This process happens internally in scatter if an array of numeric values is provided to c.
A scatter creates a PathCollection, which subclasses ScalarMappable. A ScalarMappable consists of a colormap, a normalization and an array of values. Hence the above is internalized via
plt.scatter(x,y, c=z, norm=norm, cmap=cmap)
If the minimum and maximum data are to be used as limits for the normalization, you may leave that argument out.
plt.scatter(x,y, c=z, cmap=cmap)
This is the reason that the output in the question will always be purple and yellow dots, independent of the values provided to c.
Coming back to the requirement of mapping an array of 0 and 1 to black and green color you may now look at the colormaps provided by matplotlib and look for a colormap which comprises black and green. E.g. the nipy_spectral colormap
Here black is at the start of the colormap and green somewhere in the middle, say at 0.5. One would hence need to set vmin to 0, and vmax, such that vmax*0.5 = 1 (with 1 the value to be mapped to green), i.e. vmax = 1./0.5 == 2.
import matplotlib.pyplot as plt
import numpy as np
x,y = np.random.rand(2,6)
z = np.array([0,0,1,1,0,1])
plt.scatter(x,y, c = z,
norm = plt.Normalize(vmin=0, vmax=2),
cmap = "nipy_spectral")
plt.show()
Since there may not always be a colormap with the desired colors available and since it may not be straight forward to obtain the color positions from existing colormaps, an alternative is to create a new colormaps specifically for the desired purpose.
Here we might simply create a colormap of two colors black and green.
matplotlib.colors.ListedColormap(["black", "green"])
We would not need any normalization here, because we only have two values and can hence rely on automatic normalization.
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
x,y = np.random.rand(2,6)
z = np.array([0,0,1,1,0,1])
plt.scatter(x,y, c = z, cmap = mcolors.ListedColormap(["black", "green"]))
plt.show()
First, to set the colors according to the values in y, you can do this:
color = ['red' if i==0 else 'green' for i in y]
plt.scatter(X[:,0], X[:,1], c=color)
Now talking about scatter() and cmap.
ColorMaps are used to provide colors from float values. See this documentation for reference on colormaps.
For values between 0 to 1, a color is chosen from these colormaps.
For example:
plt.cm.Spectral(0.0)
# (0.6196078431372549, 0.00392156862745098, 0.25882352941176473, 1.0) #<== magenta
plt.cm.Spectral(1.0)
# (0.3686274509803922, 0.30980392156862746, 0.6352941176470588, 1.0) #<== blue
plt.cm.Spectral(1)
# (0.6280661284121491, 0.013302575932333718, 0.26082276047673975, 1.0)
Note that the results of 1.0 and 1 are different in above code, because the int and floats are handled differently as mentioned in documentation of __call__() here:
For floats, X should be in the interval [0.0, 1.0] to return the
RGBA values X*100 percent along the Colormap line.
For integers, X should be in the interval [0, Colormap.N) to
return RGBA values indexed from the Colormap with index X.
Please look at this answer for more better explanation about colormaps:-
https://stackoverflow.com/a/25408562/3374996
In your y, you have 0 and 1, so the RGBA values shown in above code are used (which are representing two ends of the Spectral colormap).
Now here's how c and cmap parameters in plt.scatter() interact with each other.
_______________________________________________________________________
|No | type of x, y | c type | values in c | result |
|___|______________|__________|_____________|___________________________|
|1 | single | scalar | numbers | cmap(0.0), no matter |
| | point | | | what the value in c |
|___|______________|__________|_____________|___________________________|
|2 | array of | array | numbers | normalize the values in c,|
| | points | | | cmap(normalized val in c) |
|___|______________|__________|_____________|___________________________|
|3 | scalar or | scalar or| RGBA Values,| no use of cmap, |
| | array | array |Color Strings| use colors from c |
|___|______________|__________|_____________|___________________________|
Now once the actual colors are finalized, then cycles through the colors for each point in x, y. If the size of x, y is equal to or less than size of colors in c, then you get perfect mapping, or else olders colors are used again.
Here's an example to illustrate this:
# Case 1 from above table
# All three points get the same color = plt.cm.Spectral(0)
plt.scatter(x=0.0, y=0.2, c=0, cmap=plt.cm.Spectral)
plt.scatter(x=0.0, y=0.3, c=1, cmap=plt.cm.Spectral)
plt.scatter(x=0.0, y=0.4, c=1.0, cmap=plt.cm.Spectral)
# Case 2 from above table
# The values in c are normalized
# highest value in c gets plt.cm.Spectral(1.0)
# lowest value in c gets plt.cm.Spectral(0.0)
# Others in between as per normalizing
# Size of arrays in x, y, and c must match here, else error is thrown
plt.scatter([0.1, 0.1, 0.1, 0.1, 0.1], [0.2, 0.3, 0.4, 0.5, 0.6],
c=[1, 2, 3, 4, 5], cmap=plt.cm.Spectral)
# Case 3 from above table => No use of cmap here,
# blue is assigned to the point
plt.scatter(x=0.2, y=0.3, c='b')
# You can also provide rgba tuple
plt.scatter(x=0.2, y=0.4, c=plt.cm.Spectral(0.0))
# Since a single point is present, the first color (green) is given
plt.scatter(x=0.2, y=0.5, c=['g', 'r'])
# Same color 'cyan' is assigned to all values
plt.scatter([0.3, 0.3, 0.3, 0.3, 0.3], [0.2, 0.3, 0.4, 0.5, 0.6],
c='c')
# Colors are cycled through points
# 4th point will get again first color
plt.scatter([0.4, 0.4, 0.4, 0.4, 0.4], [0.2, 0.3, 0.4, 0.5, 0.6],
c=['m', 'y', 'k'])
# Same way for rgba values
# Third point will get first color again
plt.scatter([0.5, 0.5, 0.5, 0.5, 0.5], [0.2, 0.3, 0.4, 0.5, 0.6],
c=[plt.cm.Spectral(0.0), plt.cm.Spectral(1.0)])
Output:
Go through the comments in the code and location of points along with the colors to understand thoroughly.
You can also replace the param c with color in the code of Case 3 and the results will still be same.
This question already has an answer here:
imshow(img, cmap=cm.gray) shows a white for 128 value
(1 answer)
Closed 4 years ago.
So this seems like a bug, but it could be intended behavior.
My code is as follows:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
# array[0, 0] = 0
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary)
pyplot.show()
The result is a white image and not a black one as expected:
What's weird about this behavior is that uncommenting one line an changing one pixel seemingly "fixes" the problem:
Closest explanation that I found online, was:
[...] The issue is that when initialising the image with a uniform array, the minimum and maximum of the colormap are identical. As we are only changing the data, not the colormap, all images are shown as being of uniform colour.
With that explanation in mind, how do I fix this behavior?
If the vmin and vmax parameters of imshow are left unspecified, imshow sets them to be
vmin = array.min() # in this case, vmin=1
vmax = array.max() # in this case, vmax=1
It then normalizes the array values to fall between 0 and 1, using matplotlib.colors.Normalize by default.
In [99]: norm = mcolors.Normalize(vmin=1, vmax=1)
In [100]: norm(1)
Out[100]: 0.0
Thus each point in array is mapped to the color associated with 0.0:
In [101]: plt.cm.binary(0)
Out[101]: (1.0, 1.0, 1.0, 1.0) # white
Usually array will contain a variety of values and matplotlib's normalization will just "do the right thing" for you automatically. However, in these corner cases where array consists of only one value, you may need to set vmin and vmax explicitly:
import matplotlib.pyplot as pyplot
import numpy as np
array = np.ones([10, 10])
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array, cmap=pyplot.cm.binary, vmin=0, vmax=1)
pyplot.show()
You can sidestep this problem by using explicit colors instead of color mapping:
array = np.zeros((10, 10, 3), 'u1')
#array[0, 0, :] = 255
fig, ax = pyplot.subplots(figsize=(10, 5))
ax.imshow(array)
pyplot.show()
This way, zero means black and (255,255,255) means white (in RGB).