首页 > 解决方案 > Python:对 matplotlib 颜色和阴影使用字典

问题描述

我正在尝试使用字典来控制 matplotlib 图上填充的颜色和阴影,使用fill_betweenx().

我已经成功使用下面示例中的列表。但是,我正在努力弄清楚如何以类似的方式使用字典。目的是字典第一部分中的数字与数据框中的一列相关,当我绘制数据时,它应该从字典中查找相关的阴影和颜色参数。

实现这一目标的最佳方法是什么?

这是我想用来代替列表的示例字典

example_dict = {1:{'lith':'sandstone', 'hatch':'.', 'color':'yellow'},
               2:{'lith':'fine sand', 'hatch':'..', 'color':'yellow'}, 
               3:{'lith':'mudstone', 'hatch':'-', 'color':'green'},
               4:{'lith':'laminated shale', 'hatch':'--', 'color':'green'}}

使用列表的工作代码。

import matplotlib.pyplot as plt

y = [0, 1]
x = [1, 1]

fig, axes = plt.subplots(ncols=4,nrows=1, sharex=True, sharey=True,
                         figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})

colors = ['yellow', 'yellow', 'green', 'green']
hatchings = ['.', '..', '-', '--']

for ax, color, hatch in zip(axes.flat, colors, hatchings):
    ax.plot(x, y)
    ax.fill_betweenx(y, 0, 1, facecolor=color, hatch=hatch)
    ax.set_xlim(0, 0.1)
    ax.set_ylim(0, 1)
    ax.set_title(str(hatch))

plt.tight_layout()
plt.show()

这会产生:
matplotlib 用列表孵化

标签: pythondictionarymatplotlib

解决方案


只需将您迭代的内容替换为 dict 键,然后访问代码中的颜色或阴影:

import matplotlib.pyplot as plt

y = [0, 1]
x = [1, 1]

fig, axes = plt.subplots(ncols=4,nrows=1, sharex=True, sharey=True,
                         figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})
example_dict = {1:{'lith':'sandstone', 'hatch':'.', 'color':'yellow'},
               2:{'lith':'fine sand', 'hatch':'..', 'color':'yellow'}, 
               3:{'lith':'mudstone', 'hatch':'-', 'color':'green'},
               4:{'lith':'laminated shale', 'hatch':'--', 'color':'green'}}

for ax, key in zip(axes.flat, example_dict.keys()):
    ax.plot(x, y)
    ax.fill_betweenx(y, 0, 1, facecolor=example_dict[key]['color'], hatch=example_dict[key]['hatch'])
    ax.set_xlim(0, 0.1)
    ax.set_ylim(0, 1)
    ax.set_title(str(example_dict[key]['hatch']))

plt.tight_layout()
plt.show()

推荐阅读