I have made some boxplots, similar to this:
Here is the code:
plt.figure(figsize = (16, 8))
bp4 = plt.boxplot([X_e[X_e.index.month == m] for m in range(1, 13)], labels = months_names, vert = True)
plt.setp(bp4["medians"], color = "red")
plt.setp(bp4["boxes"], color = "blue")
plt.setp(bp4["whiskers"], color = "blue", linestyle = "--")
plt.setp(bp4["fliers"], color = "black", marker = " ")
plt.xlabel("Month")
plt.ylabel("Temperature (ºC)")
plt.title("Month-wise Boxplots for the Extreme Maximum Temperatures Series from 1980-12-31 to 2019-12-31")
plt.show()
I want to fill the boxplot colors in a continuous scale like a heatmap (for example from 25 to 40; blue to red). Any idea how to do that? Something like this (but in vertical) with a known scale that I can use in temperature boxplots from other areas:
Thanks in advance!
CodePudding user response:
Since you didn't provide data, I'm going to use my own:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import matplotlib.cm as cm
from matplotlib.patches import PathPatch
data_1 = np.random.normal(100, 10, 200)
data_2 = np.random.normal(90, 20, 200)
data_3 = np.random.normal(80, 30, 200)
data_4 = np.random.normal(70, 40, 200)
data = [data_1, data_2, data_3, data_4]
values = [t.mean() for t in data]
# create a normalizer
norm = Normalize(vmin=min(values), vmax=max(values))
# normalize values
norm_values = norm(values)
# choose a colormap
cmap = cm.magma
# create colors
colors = cmap(norm_values)
# map values to a colorbar
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
mappable.set_array(colors)
fig1, ax1 = plt.subplots()
ax1.set_title('Basic Plot')
ba = ax1.boxplot(data, patch_artist=True)
patches = ba["boxes"]
for p, c in zip(patches, colors):
p.set_facecolor(c)
cb = fig1.colorbar(mappable)
cb.set_label("Mean")