python - 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()
解决方案
只需将您迭代的内容替换为 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()
推荐阅读
- java - Java 舍入小数点后两位数,无 Math.round、BigDecimal 等
- javascript - addeventlistener 构建了多次
- json - 无法使用 json 正文发布 http 请求,因为 'dart:convert' 包中的 jsonEncode 方法添加了转义字符
- java - 如何使用 oshi 远程监控 Linux 服务器的性能状态?
- spring-boot - 多个 Zuul Gate-gateway 以减少流量
- java - 如何在机器人框架中使用“选择文件”关键字上传文件
- php - 条纹税计算
- node.js - PM2 可以运行命令行启动脚本吗?
- php - laravel 查询多对多
- java - 序列化 JSON 字符串作为 JSON 中的值