使用Matplotlib绘制不同颜色的带箭头的线实例

所属分类: 脚本专栏 / python 阅读数: 728
收藏 0 赞 0 分享

周五的时候计算出来一条线路,但是计算出来的只是类似与

0->10->19->2->..0

这样的线路只有写代码的人才能看的懂无法直观的表达出来,让其它同事看的不清晰,所以考虑怎样直观的把线路图画出来。

&esp; 当然是考虑用matplotlib了,

导入相关的库

import matplotlib.pyplot as plt
import numpy
import matplotlib.colors as colors
import matplotlib.cm as cmx

后面两个主要是用于处理颜色的。

准备数据

 _locations = [
    (4, 4), # depot
    (4, 4), # unload depot_prime
    (4, 4), # unload depot_second
    (4, 4), # unload depot_fourth
    (4, 4), # unload depot_fourth
    (4, 4), # unload depot_fifth
    (2, 0),
    (8, 0), # locations to visit
    (0, 1),
    (1, 1),
    (5, 2),
    (7, 2),
    (3, 3),
    (6, 3),
    (5, 5),
    (8, 5),
    (1, 6),
    (2, 6),
    (3, 7),
    (6, 7),
    (0, 8),
    (7, 8)
  ]

画图

plt.figure(figsize=(10, 10))
p1 = [l[0] for l in _locations]
p2 = [l[1] for l in _locations]
plt.plot(p1[:6], p2[:6], 'g*', ms=20, label='depot')
plt.plot(p1[6:], p2[6:], 'ro', ms=15, label='customer')
plt.grid(True)
plt.legend(loc='lower left')

way = [[0, 12, 18, 17, 16, 4, 14, 10, 11, 13, 5], [0, 6, 9, 8, 20, 3], [0, 19, 21, 15, 7, 2]]  # 

cmap = plt.cm.jet
cNorm = colors.Normalize(vmin=0, vmax=len(way))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

for k in range(0, len(way)):
  way0 = way[k]
  colorVal = scalarMap.to_rgba(k)
  for i in range(0, len(way0)-1):
    start = _locations[way0[i]]
    end = _locations[way0[i+1]]
#     plt.arrow(start[0], start[1], end[0]-start[0], end[1]-start[1], length_includes_head=True,
#         head_width=0.2, head_length=0.3, fc='k', ec='k', lw=2, ls=lineStyle[k], color='red')
    plt.arrow(start[0], start[1], end[0]-start[0], end[1]-start[1], 
         length_includes_head=True, head_width=0.2, lw=2,
         color=colorVal)
plt.show()
cmap = plt.cm.jet
cNorm = colors.Normalize(vmin=0, vmax=len(way))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

cmap可以理解为颜色库,cNorm设置颜色的范围,有几条线路就设置几种颜色,scalarMap颜色生成完毕。最后在绘图的时候,根据索引获得相应的颜色就可以了。

结果如下:

补充知识:Python包matplotlib绘图--如何标注某点--附代码

# -*- coding: utf-8 -*-
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')

plt.rcParams['font.sans-serif'] = ['SimHei'] #解决中文显示
plt.rcParams['axes.unicode_minus'] = False #解决符号无法显示

x=np.array([1,2,3,4,5,6,7,8])
y1=np.array([3,5,35,300,800,600,1200,4000])
y2=np.array([8,14,94,703,1300,1660,2801,12768])

fig1 = plt.figure()

ax = plt.axes()
ax.plot(x, y2,label='时间/秒')
ax.set(xlabel='目标函数个数', ylabel='程序运行时间',title='多目标收敛速度')

plt.hlines(703, 0, 4, colors='r', linestyle="--")
plt.text(0, 703, "703")
plt.hlines(1300, 0, 5, colors='g', linestyle="--")
plt.text(0, 1300, "1300")

# annotate 
plt.annotate("703秒", (4,703), xycoords='data',
       xytext=(4.2, 2000), 
       arrowprops=dict(arrowstyle='->')) 
plt.annotate("94秒", (3,94), xycoords='data',
       xytext=(3.5, 2000), 
       arrowprops=dict(arrowstyle='->')) 
plt.annotate("14秒", (2,14), xycoords='data',
       xytext=(2.5, 2000), 
       arrowprops=dict(arrowstyle='->')) 
plt.annotate("8秒", (1,8), xycoords='data',
       xytext=(1.5, 2000), 
       arrowprops=dict(arrowstyle='->')) 
plt.legend()
plt.show()
fig1.savefig('my_figure1.png')

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch

# Use seaborn to change the default graphics to something nicer
import seaborn as sns
# And set a nice color palette
sns.set_color_codes('deep')

# Create the plot object
fig, ax = plt.subplots(figsize=(5, 4))
x = np.linspace(0, 1000)

# Add finishing constraint: x2 <= 100/2 - x1/2
plt.plot(x, 50/4 - 3*x/4, linewidth=3, label='First constraint')
plt.fill_between(x, 0, 100/2 - x/2, alpha=0.1)

# Add carpentry constraint: x2 <= 80 - x1
plt.plot(x, 30 - 2*x, linewidth=3, label='Second constraint')
plt.fill_between(x, 0, 100 - 2*x, alpha=0.1)

# Add non-negativity constraints
plt.plot(np.zeros_like(x), x, linewidth=3, label='$x$ Sign restriction')
plt.plot(x, np.zeros_like(x), linewidth=3, label='$y$ Sign restriction')

#====================================================
# This part is different from giapetto_feasible.py
# Plot the possible (x1, x2) pairs
pairs = [(x, y) for x in np.arange(101)
        for y in np.arange(101)
        if (300*x + 400*y) <= 5000
        and (200*x + 100*y) <= 3000]

# Split these into our variables
chairs, tables = np.hsplit(np.array(pairs), 2)

# Caculate the objective function at each pair
z =8*chairs + 9*tables

# Plot the results
plt.scatter(chairs, tables, c=z, cmap='jet', edgecolor='gray', alpha=0.5, label='Profit at each point', zorder=3)

# Colorbar
cb = plt.colorbar()
cb.set_label('Profit Colormap ($)')
#====================================================

# Labels and stuff
plt.xlabel('Package A')
plt.ylabel('Package B')
plt.xlim(-0.5, 20)
plt.ylim(-0.5, 20)
plt.legend()
fig01 = plt.figure()
plt.show()

以上这篇使用Matplotlib绘制不同颜色的带箭头的线实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

使用Python写一个量化股票提醒系统

这篇文章主要介绍了小白用Python写了一个股票提醒系统,迷你版量化系统,完美的实现了实时提醒功能,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python绘制的二项分布概率图示例

这篇文章主要介绍了Python绘制的二项分布概率图,涉及Python基于numpy、math的数值运算及matplotlib图形绘制相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python Learning 列表的更多操作及示例代码

这篇文章主要介绍了Python Learning-列表的更多操作,需要的朋友可以参考下
收藏 0 赞 0 分享

关于python列表增加元素的三种操作方法

这篇文章主要介绍了关于python列表增加元素的几种操作方法,主要有insert方法,extend方法和append方法,每种方法给大家介绍的非常详细,需要的朋友可以参考下
收藏 0 赞 0 分享

如何在python字符串中输入纯粹的{}

这篇文章主要介绍了如何在python字符串中输入纯粹的{}以及python字符串连接的三种方法,需要的朋友可以参考下
收藏 0 赞 0 分享

浅谈Django的缓存机制

这篇文章主要介绍了浅谈Django的缓存机制,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Django 限制用户访问频率的中间件的实现

这篇文章主要介绍了Django 限制用户访问频率的中间件的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

示例详解Python3 or Python2 两者之间的差异

这篇文章主要介绍了Python3 or Python2?示例详解两者之间的差异,在本文中给大家介绍的非常详细,需要的朋友可以参考下
收藏 0 赞 0 分享

Python wxpython模块响应鼠标拖动事件操作示例

这篇文章主要介绍了Python wxpython模块响应鼠标拖动事件操作,结合实例形式分析了Python使用wxpython模块创建窗口、绑定事件及相应鼠标事件相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

使用Python实现一个栈判断括号是否平衡

栈(Stack)在计算机领域是一个被广泛应用的集合,栈是线性集合,访问都严格地限制在一段,叫做顶(top)。这篇文章主要介绍了使用Python实现一个栈判断括号是否平衡,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多