Python读取多列数据以及用matplotlib制作图表方法实例

多列数据的读入以及处理

这次我们用到的数据是煤炭5500周价格的最高价和最低价。左侧为价格的数据表格,右侧为日期。

一、导入数据

这里我们就直接跳过讲解,如有不懂的,详见上一篇博客。见代码。

import matplotlib.pyplot as plt
import re
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体
plt.rcParams['axes.unicode_minus'] = False # 设置正负号
# 导入数据,日期
with open('日期.csv', encoding='gbk') as oo:
  day = oo.read()
day_str = day.replace('\n', ',') # 换行替换成逗号
day_list = re.split('[,]', day_str)
list_days = []
for s in range(len(day_list)-1): # 获得时间
  list_days.append(day_list[s])
# 将x转换成时间类型
# 导入数据,金额
with open('煤炭5500周价格波动数据.csv', encoding='gbk') as pp:
  sk = pp.read()
ll = sk.replace('\n', ',') # 换行替换成逗号
list_1 = re.split('[,]', ll) # 分割数据
list_2 = []
for s in range(len(list_1)-1):
  list_2.append(int(float(list_1[s])))

现在我们已经讲数据读取到相关的列表里,输出一下。

输出结果:
['2019/12/27', '2019/12/20', '2019/12/13', '2019/12/6', '2019/11/29', '2019/11/22', '2019/11/15', '2019/11/8', '2019/11/1', '2019/10/25', '2019/10/18', '2019/10/11', '2019/9/27', '2019/9/20', '2019/9/12', '2019/9/12', '2019/9/6', '2019/8/30', '2019/8/23', '2019/8/16', '2019/8/9', '2019/8/2', '2019/7/26', '2019/7/19', '2019/7/12', '2019/7/5', '2019/6/28', '2019/6/21', '2019/6/14', '2019/6/7', '2019/5/31', '2019/5/24', '2019/5/17', '2019/5/10', '2019/4/26', '2019/4/19', '2019/4/12', '2019/4/5', '2019/3/29', '2019/3/22', '2019/3/15', '2019/3/8', '2019/3/1', '2019/2/22', '2019/2/15', '2019/2/1', '2019/1/25', '2019/1/18', '2019/1/18', '2019/1/11', '2019/1/4', '2018/12/28']
[550, 555, 550, 555, 550, 555, 550, 555, 550, 555, 550, 555, 550, 555, 550, 555, 560, 565, 570, 575, 575, 580, 580, 585, 585, 590, 585, 590, 585, 590, 585, 590, 580, 585, 580, 585, 580, 590, 575, 585, 580, 590, 595, 600, 590, 600, 590, 595, 600, 605, 605, 615, 600, 610, 590, 600, 590, 600, 590, 600, 595, 600, 610, 620, 615, 620, 615, 620, 615, 625, 620, 625, 630, 640, 620, 630, 620, 625, 620, 630, 625, 630, 635, 645, 615, 625, 600, 605, 600, 605, 585, 590, 590, 595, 590, 595, 590, 595, 580, 590, 585, 595, 575, 580]

二、处理价格数据

我们可以看到0,2,4,6,8.......等偶数位的数值是周最低价,而单数位的数值是周最高价。我们可以用循环的方式读取到相关的数据。

代码如下。

这样就可以把数据进行分组了。以此类推,可以导入多列数据。

根据观察可以看到,时间列表是以降序的方式排列的,我们需要将数据转置过来,让列表数据改为升序。方法一、调整导入的CSV文件的数据顺序。方法二、我们引入reversed()函数。该函数有两种写法,作用主要是将列表,range(),字典里的数据进行逆向排列。

逆转对象:list_x
写法一、
xxx = reversed(list_x)
写法二、
直接使用
list(reversed(list_x))
aaa = reversed(list_average) 转置一个作为样例
# 以上分割取得list_high,low,average
# 设置x轴,y轴标签,设置表格标题
plt.xlabel('时间')
plt.ylabel('价格')
plt.title('最高价/最低价/均价周期波动图')
plt.legend(loc='upper right')
plt.figure(figsize=(9, 8))输出图片大小900px*800px

图表制作

需要的数据我们已经处理好了,接着就是生成图表。

import matplotlib.pyplot as plt
import re
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体
plt.rcParams['axes.unicode_minus'] = False # 设置正负号
# 导入数据,日期
with open('日期.csv', encoding='gbk') as oo:
  day = oo.read()
day_str = day.replace('\n', ',') # 换行替换成逗号
day_list = re.split('[,]', day_str)
list_days = []
for s in range(len(day_list)-1): # 获得时间
  list_days.append(day_list[s])
print(list_days)
# 将x转换成时间类型
# 导入数据,金额
with open('煤炭5500周价格波动数据.csv', encoding='gbk') as pp:
  sk = pp.read()
ll = sk.replace('\n', ',') # 换行替换成逗号
list_1 = re.split('[,]', ll) # 分割数据
list_2 = []
for s in range(len(list_1)-1):
  list_2.append(int(float(list_1[s])))
print(list_2)
list_high = [] # 最高
list_low = [] # 最低
list_average = [] # 均值
for k in range(len(list_2)):
  if k % 2 == 0:
    list_low.append(list_2[k])
    list_average.append((list_2[k]+list_2[k+1])/2)
  else:
    list_high.append(list_2[k])
aaa = reversed(list_average)
# 以上分割取得list_high,low,average
# 设置x轴,y轴标签,设置表格标题
plt.xlabel('时间')
plt.ylabel('价格')
plt.title('最高价/最低价/均价周期波动图')
# 设置标注

plt.figure(figsize=(9, 8))

# 制作折现图
plt.plot(range(len(list_low)), list(reversed(list_high)), label='最高价', color='brown',marker='o',markerfacecolor='c',markersize='5')
plt.plot(range(len(list_low)), list(reversed(list_low)), label='最低价', color='skyblue',marker='s',markerfacecolor='r',markersize='5')
plt.plot(range(len(list_low)), list(reversed(list_average)), label='均价', color='lawngreen',marker='h',markerfacecolor='coral',markersize='5')
# 设置标注
plt.legend(loc='upper right') # 右上upper right 右下lower right
plt.show()

这是到目前我们制作出来的折线图

替换x轴坐标点更改成日期

这里我们使用到plt.xticks()

书写格式:
plt.xticks(被替换的数值(数据长的的列表),替换的数据,数据方向(默认横向))
plt.xticks(range(len(list_low)), list(reversed(list_days)), rotation='vertical')
vertical:数值方向,也可以写角度。

到这了我们就完成了全部的代码。

结束:最终代码

import matplotlib.pyplot as plt
import re
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体
plt.rcParams['axes.unicode_minus'] = False # 设置正负号
# 导入数据,日期
with open('日期.csv', encoding='gbk') as oo:
  day = oo.read()
day_str = day.replace('\n', ',') # 换行替换成逗号
day_list = re.split('[,]', day_str)
list_days = []
for s in range(len(day_list)-1): # 获得时间
  list_days.append(day_list[s])
print(list_days)
# 将x转换成时间类型
# 导入数据,金额
with open('煤炭5500周价格波动数据.csv', encoding='gbk') as pp:
  sk = pp.read()
ll = sk.replace('\n', ',') # 换行替换成逗号
list_1 = re.split('[,]', ll) # 分割数据
list_2 = []
for s in range(len(list_1)-1):
  list_2.append(int(float(list_1[s])))
print(list_2)
list_high = [] # 最高
list_low = [] # 最低
list_average = [] # 均值
for k in range(len(list_2)):
  if k % 2 == 0:
    list_low.append(list_2[k])
    list_average.append((list_2[k]+list_2[k+1])/2)
  else:
    list_high.append(list_2[k])
aaa = reversed(list_average)
# 以上分割取得list_high,low,average
# 设置x轴,y轴标签,设置表格标题
plt.xlabel('时间')
plt.ylabel('价格')
plt.title('最高价/最低价/均价周期波动图')
# 设置标注

plt.figure(figsize=(9, 8))

plt.xticks(range(len(list_low)), list(reversed(list_days)), rotation='vertical')
# 设置折现图
plt.plot(range(len(list_low)), list(reversed(list_high)), label='最高价', color='brown',marker='o',markerfacecolor='c',markersize='5')
plt.plot(range(len(list_low)), list(reversed(list_low)), label='最低价', color='skyblue',marker='s',markerfacecolor='r',markersize='5')
plt.plot(range(len(list_low)), list(reversed(list_average)), label='均价', color='lawngreen',marker='h',markerfacecolor='coral',markersize='5')
# 设置标注
plt.legend(loc='upper right')
plt.show()

结果示意图:

总结

到此这篇关于Python读取多列数据以及用matplotlib制作图片的文章就介绍到这了,更多相关Python读取多列数据用matplotlib制作图片内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python matplotlib图例放在外侧保存时显示不完整问题解决

    上次说到的,使用如下代码保存矢量图时,放在外侧的图例往往显示不完整: import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x1 = np.random.uniform(-10, 10, size=20) x2 = np.random.uniform(-10, 10, size=20) #print(x1) #print(x2) number = [] x11 = [] x12 = [] for i

  • python Matplotlib模块的使用

    一.Matplotlib简介与安装 Matplotlib也就是Matrix Plot Library,顾名思义,是Python的绘图库.它可与NumPy一起使用,提供了一种有效的MATLAB开源替代方案.它也可以和图形工具包一起使用,如PyQt和wxPython. 安装方式:执行命令 pip install matplotlib 一般常用的是它的子包PyPlot,提供类似MATLAB的绘图框架. 二.使用方法 1.绘制一条直线 y = 3 * x + 4,其中 x 在(-2, 2),取100个点

  • Python之Matplotlib文字与注释的使用方法

    可视化对于大家来说确实是有关的,因为确实是直观的,每一组大数据如果可以用可视化进行展示的话可以让大家豁然开朗.但在另外一些场景中,辅之以少量的文字提示(textual cue)和标签是必不可少的.虽然最基本的注释(annotation)类型可能只是坐标轴标题与图标题,但注释可远远不止这些.让我们可视化一些数据,看看如何通过添加注释来更恰当地表达信息. 首先导入画图需要用到的一些函数: import matplotlib.pyplot as plt import matplotlib as mpl

  • Python matplotlib 绘制双Y轴曲线图的示例代码

    Matplotlib简介 Matplotlib是非常强大的python画图工具 Matplotlib可以画图线图.散点图.等高线图.条形图.柱形图.3D图形.图形动画等. Matplotlib安装 pip3 install matplotlib#python3 双X轴的 可以理解为共享y轴 ax1=ax.twiny() ax1=plt.twiny() 双Y轴的 可以理解为共享x轴 ax1=ax.twinx() ax1=plt.twinx() 自动生成一个例子 x = np.arange(0.,

  • Python matplotlib读取excel数据并用for循环画多个子图subplot操作

    读取excel数据需要用到xlrd模块,在命令行运行下面命令进行安装 pip install xlrd 表格内容大致如下,有若干sheet,每个sheet记录了同一所学校的所有学生成绩,分为语文.数学.英语.综合.总分 考号 姓名 班级 学校 语文 数学 英语 综合 总分 ... ... ... ... 136 136 100 57 429 ... ... ... ... 128 106 70 54 358 ... ... ... ... 110.5 62 92 44 308.5 画多张子图需要

  • Python Matplotlib绘图基础知识代码解析

    1.Figure和Subplot import numpy as np import matplotlib.pyplot as plt #创建一个Figure fig = plt.figure() #不能通过空figure绘图,必须使用add_subplot创建一个或多个subplot #图像为2x2,第三个参数为当前选中的第几个 ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot

  • python使用matplotlib绘制折线图的示例代码

    示例代码如下: #!/usr/bin/python #-*- coding: utf-8 -*- import matplotlib.pyplot as plt # figsize - 图像尺寸(figsize=(10,10)) # facecolor - 背景色(facecolor="blue") # dpi - 分辨率(dpi=72) fig = plt.figure(figsize=(10,10),facecolor="blue") #figsize默认为4,

  • python matplotlib库的基本使用

    matplotlib简介 如果你在大学里参加过数学建模竞赛或者是用过MATLAB的话,相比会对这一款软件中的画图功能印象深刻.MATLAB可以做出各种函数以及数值分布图像非常的好用和方便.如果你没用过呢也没关系,知道这么回事就好了.MATLAB虽然好用,但毕竟是收费软件,而且相比于MATLAB,很多人更喜欢Python的语法. 所以呢MATLAB就被惦记上了,后来有大神仿照MATLAB当中的画图工具,也在Python当中开发了一个类似的作图工具.这也就是我们今天这篇文章要讲的matplotlib

  • 解决Python Matplotlib绘图数据点位置错乱问题

    在绘制正负样本在各个特征维度上的CDF(累积分布)图时出现了以下问题: 问题具体表现为: 1.几个负样本的数据点位置倒错 2.X轴刻度变成了乱七八糟一团鬼东西 最终解决办法 造成上述情况的原因其实是由于输入matplotlib.plot()函数的数据x_data和y_data从CSV文件中直接导入后格式为string,因此才会导致所有数据点的x坐标都被直接刻在了x轴上,且由于坐标数据格式错误,部分点也就表现为"乱点".解决办法就是导入x,y数据后先将其转化为float型数据,然后输入p

  • Python Matplotlib简易教程(小白教程)

    简单演示 import matplotlib.pyplot as plt import numpy as np # 从[-1,1]中等距去50个数作为x的取值 x = np.linspace(-1, 1, 50) print(x) y = 2*x + 1 # 第一个是横坐标的值,第二个是纵坐标的值 plt.plot(x, y) # 必要方法,用于将设置好的figure对象显示出来 plt.show() import matplotlib.pyplot as plt import numpy as

随机推荐