难以在python 3.6中绘制颜色栏的图例 [英] Difficulty to plot legend for a color bar in python 3.6

查看:31
本文介绍了难以在python 3.6中绘制颜色栏的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

如果我理解正确,则需要三个图例手柄,每个色石一个.这可以通过使用 mpatches

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)

这篇关于难以在python 3.6中绘制颜色栏的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆