matplotlib绘制精美的折线图——另附颜色、形状查找表

0 配置及环境

  • 系统: win7 x64
  • python: 3.64 x64
  • 包: matplotlib、numpy

 本文主要是讲述如何利用python的matplotlib包来绘制精美的折线图,包括绘制折现、增加坐标轴名称、增加图例、设置颜色、设置形状、设置字体、标注点、设置图的比例大小、一张图两张y轴等

1 绘制简单的折线

 利用matplotlib绘制折线图很简单,只需要加入数据,然后设置纵横坐标范围、纵横坐标名称、图例,就可以轻易的保存或者展示图片结果。

# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
# pre-datas
x = np.arange(1, 11, 1)  # x坐标
plt.plot(x, y1, lw=1, c='red', marker='s', ms=4, label='Y1')  # 绘制y1
plt.plot(x, y2, lw=1, c='g', marker='o', label='Y2')  # 绘制y2
# plt-style 
plt.xticks(x)  # x轴的刻度
plt.xlim(0.5, 10.5)  # x轴坐标范围
plt.ylim(-500, 5800)  # y轴坐标范围
plt.xlabel('X-Name')  # x轴标注
plt.ylabel('Y-Name')  # y轴标注
plt.legend()  # 图例
plt.savefig('e:/test.png')  # 保存图片
plt.show()

图片生成结果如下:
在这里插入图片描述

2 颜色、形状查找表

绘制折线,可以有多种颜色及形状,c代表color,marker代表节点形状,ms代表marker size,label是折现名称。

plt.plot(x, y1, lw=1, c='red', marker='s', ms=4, label='Y1')

比如要控制y1为紫色线条,*状符号,就可以:

plt.plot(x, y1, lw=1, c='purple', marker='*', ms=4, label='Y1')

为了方便查找,将颜色和形状整理如下:

  1. 形状
's' : 方块状
'o' : 实心圆
'^' : 正三角形
'v' : 反正三角形
'+' : 加好
'*' : 星号
'x' : x号
'p' : 五角星
'1' : 三脚架标记
'2' : 三脚架标记
  1. 颜色
    在这里插入图片描述
  • 43
    点赞
  • 218
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要画不同颜色的两段折线图,可以使用 matplotlib 中的多个 plot 函数来实现。具体步骤如下: 1. 导入 matplotlib 库和数据: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y1 = [3, 5, 2, 7, 8, 3, 6, 9, 1, 4] y2 = [5, 4, 6, 1, 2, 7, 4, 8, 2, 6] ``` 2. 使用 plot 函数画出第一段折线,设置颜色为蓝色: ```python plt.plot(x[:5], y1[:5], color='blue') ``` 3. 使用 plot 函数画出第二段折线,设置颜色为红色: ```python plt.plot(x[4:], y1[4:], color='red') ``` 4. 使用 plot 函数画出第三段折线,设置颜色为绿色: ```python plt.plot(x[:5], y2[:5], color='green') ``` 5. 使用 plot 函数画出第四段折线,设置颜色为橙色: ```python plt.plot(x[4:], y2[4:], color='orange') ``` 6. 添加标题和图例,并显示图像: ```python plt.title('Two Lines with Different Colors') plt.legend(['Line 1', 'Line 2']) plt.show() ``` 完整代码如下: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y1 = [3, 5, 2, 7, 8, 3, 6, 9, 1, 4] y2 = [5, 4, 6, 1, 2, 7, 4, 8, 2, 6] plt.plot(x[:5], y1[:5], color='blue') plt.plot(x[4:], y1[4:], color='red') plt.plot(x[:5], y2[:5], color='green') plt.plot(x[4:], y2[4:], color='orange') plt.title('Two Lines with Different Colors') plt.legend(['Line 1', 'Line 2']) plt.show() ``` 结果如下图所示: ![image.png](attachment:image.png) 同时,如果需要更多颜色形状的选择,可以参考下面的颜色形状查找: ```python colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] markers = ['.', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'] ``` 其中,colors 列中包含了常用的颜色,markers 列中包含了常用的形状。在 plot 函数中,可以通过设置 color 和 marker 参数来选择颜色形状。例如: ```python plt.plot(x, y, color='r', marker='o') ``` 上述代码将画出红色的圆点形状折线。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值