matplotlib: how can you specify colour levels in a 2d historgram

  • Last Update :
  • Techknowledgy :
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors
import from_levels_and_colors

x = np.random.rand(400)
y = np.random.rand(400)
Z, xedges, yedges = np.histogram2d(x, y, bins = 10)
Z = Z - 2.
# - 1 0 3 6 9
cmap, norm = from_levels_and_colors([-1, 0, 3, 6, 9, 12], ['r', 'b', 'g', 'y', 'm']) # mention levels and colors here
plt.pcolormesh(xedges, yedges, Z, cmap = cmap, norm = norm)
plt.colorbar()
plt.show()

Add vmin and vmax parameters with equal absolute values

plt.pcolormesh(xedges, yedges, Z, cmap = CM.RdBu_r, vmin = -7, vmax = 7)

Suggestion : 2

Once you decide the bin size, it is possible to change the colour palette. Please visit the matplotlib reference page to see the available palette.,2D histograms are useful when you need to analyse the relationship between 2 numerical variables that have a huge number of values. It is useful for avoiding the over-plotted scatterplots. The following example illustrates the importance of the bins argument. You can explicitly tell how many bins you want for the X and the Y axis. The parameters of hist2d() function used in the example are: ,This post is dedicated to 2D histograms made with matplotlib, through the hist2D function.,👋 This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message onTwitter, or send an email pasting yan.holtz.data with gmail.com.

# libraries
import matplotlib.pyplot as plt
import numpy as np

# create data
x = np.random.normal(size = 50000)
y = x * 3 + np.random.normal(size = 50000)

# Big bins
plt.hist2d(x, y, bins = (50, 50), cmap = plt.cm.jet)
plt.show()

# Small bins
plt.hist2d(x, y, bins = (300, 300), cmap = plt.cm.jet)
plt.show()

# If you do not set the same values
for
X and Y, the bins won 't be a square!
plt.hist2d(x, y, bins = (300, 30), cmap = plt.cm.jet)
plt.show()
# Reds
plt.hist2d(x, y, bins = (50, 50), cmap = plt.cm.Reds)
plt.show()

# BuPu
plt.hist2d(x, y, bins = (50, 50), cmap = plt.cm.BuPu)
plt.show()
plt.hist2d(x, y, bins = (50, 50), cmap = plt.cm.Greys)
plt.colorbar()
plt.show()

Suggestion : 3

To plot a histogram with colors taken from colormap, we can use the setp() method.,How to plot data into imshow() with custom colormap in Matplotlib?,Plot a histogram with Y-axis as percentage in Matplotlib,How to plot a line graph from histogram data in Matplotlib?

Example

import numpy as np
from matplotlib
import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.random(1000)
n, bins, patches = plt.hist(data, bins = 25, density = True, color = 'red', rwidth = 0.75)
col = (n - n.min()) / (n.max() - n.min())
cm = plt.cm.get_cmap('RdYlBu')
for c, p in zip(col, patches):
   plt.setp(p, 'facecolor', cm(c))
plt.show()

Suggestion : 4

Density heatmaps can also be faceted:,How to make 2D Histograms in Python with Plotly. ,In this example we add text to 2D Histogram points. We use the values from the z attribute for the text.,See https://plotly.com/python/reference/histogram2d/ for more information and chart attribute options!

import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x = "total_bill", y = "tip")
fig.show()
import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x = "total_bill", y = "tip", nbinsx = 20, nbinsy = 20, color_continuous_scale = "Viridis")
fig.show()
import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x = "total_bill", y = "tip", marginal_x = "histogram", marginal_y = "histogram")
fig.show()
import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x = "total_bill", y = "tip", facet_row = "sex", facet_col = "smoker")
fig.show()
import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x = "total_bill", y = "tip", text_auto = True)
fig.show()
import plotly.express as px
df = px.data.iris()

fig = px.density_heatmap(df, x = "petal_length", y = "petal_width", z = "sepal_length", histfunc = "avg")
fig.show()

Suggestion : 5

We will start with grayscale images and histograms first, and then move on to colour images. We will use this image of a plant seedling as an example: ,As it pertains to images, a histogram is a graphical representation showing how frequently various colour values occur in the image. We saw in the Image Basics episode that we could use a histogram to visualise the differences in uncompressed and compressed image formats. If your project involves detecting colour changes between images, histograms will prove to be very useful, and histograms are also quite handy as a preparatory step before performing thresholding.,We can also create histograms for full colour images, in addition to grayscale histograms. We have seen colour histograms before, in the Image Basics episode. A program to create colour histograms starts in a familiar way:,Suppose we are interested in the colour histogram of one of the sensors in the well plate image, specifically, the seventh well from the left in the topmost row, which shows Erythrosin B reacting with water.

import numpy as np
import skimage.color
import skimage.io
import matplotlib.pyplot as plt %
   matplotlib widget

# read the image of a plant seedling as grayscale from the outset
image = skimage.io.imread(fname = "data/plant-seedling.jpg", as_gray = True)

# display the image
fig, ax = plt.subplots()
plt.imshow(image, cmap = "gray")
plt.show()
# create the histogram
histogram, bin_edges = np.histogram(image, bins = 256, range = (0, 1))
# configure and draw the histogram figure
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixel count")
plt.xlim([0.0, 1.0]) # < -named arguments do not work here

   plt.plot(bin_edges[0: -1], histogram) # < -or here
plt.show()
import skimage.draw

# read the image as grayscale from the outset
image = skimage.io.imread(fname = "data/plant-seedling.jpg", as_gray = True)

# display the image
fig, ax = plt.subplots()
plt.imshow(image, cmap = "gray")
plt.show()

# create mask here, using np.zeros() and skimage.draw.rectangle()
mask = np.zeros(shape = image.shape, dtype = "bool")
rr, cc = skimage.draw.rectangle(start = (199, 410), end = (384, 485))
mask[rr, cc] = True

# display the mask
fig, ax = plt.subplots()
plt.imshow(mask, cmap = "gray")
plt.show()

# mask the image and create the new histogram
histogram, bin_edges = np.histogram(image[mask], bins = 256, range = (0.0, 1.0))

# configure and draw the histogram figure
plt.figure()

plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixel count")
plt.xlim([0.0, 1.0])
plt.plot(bin_edges[0: -1], histogram)

plt.show()
# read original image, in full color
image = skimage.io.imread(fname = "data/plant-seedling.jpg")

# display the image
fig, ax = plt.subplots()
plt.imshow(image)
plt.show()
# tuple to select colors of each channel line
colors = ("red", "green", "blue")
channel_ids = (0, 1, 2)

# create the histogram plot, with three lines, one
for
# each color
plt.figure()
plt.xlim([0, 256])
for channel_id, c in zip(channel_ids, colors):
   histogram, bin_edges = np.histogram(
      image[: ,: , channel_id], bins = 256, range = (0, 256)
   )
plt.plot(bin_edges[0: -1], histogram, color = c)

plt.title("Color Histogram")
plt.xlabel("Color value")
plt.ylabel("Pixel count")

plt.show()