如何解决使用 Itertools 和 For 循环创建水平条 (Python)
我一直在玩 Matplotlib,并使用以下算法创建了一个水平条(本文底部提供了完整代码和垃圾数据)。
# Version 1
ax.broken_barh([(depth_start[0],thick[0]),(depth_start[1],thick[1]),(depth_start[2],thick[2])],(25,0.8),facecolors=('tab:brown','tab:blue','tab:green'))
产生以下图形输出:
所以我一直试图通过引入 itertools
我设法将上述代码简化为第 2 版:
# Version 2
for i in thick:
ax.broken_barh([(next(cycle_depth),next(cycle_thick))],(15,facecolors=(next(cycle_colour)))
太好了,这也会以相同的顺序生成相同颜色的上述条。
问题
但我正在努力实现我的下一个目标,即用使用 facecolors=('tab:brown','tab:green')
的 function
替换 for loop
。理想情况下,此功能会根据粗细为每个条形选择正确的颜色。由于函数不断返回与 else
语句关联的值(见下图),因此所有 3 个条形都返回棕色。
我曾尝试用 next(cycle_thick)
代替函数中的变量 cycle_think,但只有一种颜色再次正确。
colour_checker() 函数如下:
def colour_checker():
if cycle_thick == 10:
return 'tab:green'
elif cycle_thick == 20:
return 'tab:blue'
else:
return 'tab:brown'
# Version 3
for i in thick:
ax.broken_barh([(next(cycle_depth),(10,facecolors=colour_checker())
欢迎任何提示或建议!
import itertools
import matplotlib.pyplot as plt
# Junk data in the form of lists
depth_start = [90,70,40] # top of lithology
thick = [30,20,10] # thickness for each lithology
colour = ('tab:brown','tab:green')
# Lists to be cycled through
cycle_colour = itertools.cycle(colour)
cycle_depth = itertools.cycle(depth_start)
cycle_thick = itertools.cycle(thick)
#setting up the plot
fig,ax = plt.subplots()
def colour_checker():
if cycle_thick == [0]:
return 'tab:green'
elif cycle_thick == [1]:
return 'tab:blue'
else:
return 'tab:brown'
# Version 1
ax.broken_barh([(depth_start[0],'tab:green'))
# Version 2
for i in thick:
ax.broken_barh([(next(cycle_depth),facecolors=(next(cycle_colour)))
# Version 3
for i in thick:
ax.broken_barh([(next(cycle_depth),facecolors=colour_checker())
ax.set_ylabel('X_UTM Position')
ax.set_xlabel('MAMSL')
plt.show()
解决方法
由于结果的意图不明确,我为我能想象的所有三个版本都创建了示例。
Trying to send command for object without authority. Targeter.CmdSetTarget
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。