难以在python 3.6中绘制颜色栏的图例

时间:2019-06-07 14:35:54

标签: python matplotlib plot legend

我有3种颜色(ccc)用于3种不同类型的岩石(d2),我想为颜色栏绘制带有矩形的图例。我已经搜索过,但是找不到正确的代码。你能帮我吗?

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)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则需要三个图例手柄,每个有色宝石一个。这可以通过使用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)

enter image description here