I have 3 colors (ccc) for 3 different types of rock (d2) and I would like to plot a legend with rectangles for my color bar. I already searched about it, but couldn't find the right code. Could you help me?
import numpy as np
import pandas as pd
import matplotlib.colors as colors
import matplotlib.pyplot as plt
d = {'Porosity': [20, 5, 15, 7, 30], 'Permeability': [2500, 100, 110, 40,
2200], 'Lithology': ['Sandstone', 'Shale', 'Shale', 'Halite', 'Sandstone'],
'Depth': [1000, 1500, 2000, 2500, 3000]}
df = pd.DataFrame(d)
d2 = {'Sandstone': 1, 'Shale': 2, 'Halite': 3}
lito = df['Lithology']
df['Label'] = lito.map(d2)
ccc = ['darkgreen','skyblue', 'yellow']
cmap_facies = colors.ListedColormap(ccc[0:len(ccc)], 'indexed')
cluster = np.repeat(np.expand_dims(df['Label'].values, 1), 1, 1)
f, ax = plt.subplots(nrows=1, ncols=1, figsize=(2,12))
depth = df['Depth']
ax.imshow(cluster, interpolation='none', aspect='auto', cmap=cmap_facies,
vmin=1, vmax=3, extent=[0,1 ,np.max(depth),np.min(depth)])
plt.tick_params(bottom=False, labelbottom=False)
If I understood correctly, you want three legend handles, one for each colored stone. This can be done by adding custom legend handles using mpatches
import numpy as np
import pandas as pd
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches # <-- Add this import
# Your code here
hands = []
for k, col in zip(d2.keys(), ccc):
hands.append(mpatches.Patch(color=col, label=k))
plt.legend(handles=hands, loc=(1.05, 0.5), fontsize=18)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.