I'd like to plot a 1D array horizontally in matplotlib. It needs to be drawn as a bar, but different from the ordinary bar chart, its color changes according to the size of the value, which is similar to a heatmap. You can think of it as a heatmap (horizontal) with only one row.
The simulated data is as follows. It contains positive and negative values. I want the color to be white when the value is 0, then positive numbers are represented as red, and negative numbers are represented as blue. The larger the value, the darker the color.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(9)
simu_data = np.random.randint(-100000, 100000, size = 200).cumsum()
CodePudding user response:
Matplotlib has an ad hoc norm to deal with your problem, matplotlib.colors.TwoSlopeNorm
.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
np.random.seed()
diverging_cmap = np.random.choice([
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'
])
np.random.seed(9)
simu_data = np.random.randint(-100000, 100000, size = 201).cumsum()
plt.imshow(np.vstack([simu_data[None,:] for _ in range(20)]),
norm=mpl.colors.TwoSlopeNorm(vcenter=0), cmap=diverging_cmap)
plt.yticks([])
plt.colorbar()
plt.title(diverging_cmap)
plt.show()