Matplotlib:Get_started


Loading data for plotting

  • There are several common data structures we will keep coming across.
1. list eg: data = [1, 2, 3, 4, 5, 6]
2. numpy array eg: array = np.array(data)
3. pandas DataFrame eg: df = pd.DataFrame(data)
  • Loading data from files
1. The basic Python way
evens = []
with open('file_path') as f:
    for line in f.readlines():
        evens.append(line.split()[1])
2. The Numpy way
import numpy as np
np.loadtxt('file_path', delimiter='\t', usecols=1, dtype=np.int32)
  • The first parameter is the path of the data file. The delimiter parameter specifies the string used to separate values, which is a tab here. Because numpy.loadtxt() by default separate values separated by any whitespace into columns by default, this argument can be omitted here. We have set it for demonstration.
  • For usecols and dtype that specify which columns to read and what data type each column corresponds to, you may pass a single value to each, or a sequence (such as list) for reading multiple columns.
3. The Pandas way(main way)
import pandas as pd
pd.read_csv('file_path', sep='\t', usecols=1)

Plotting

import matplotlib.pylot as plt
plt.plot(data)
plt.plot(data, data**2)
plt.plot(data, data**2, label='x^2')
plt.legend()       #To label the curve with a legend
  • To label the curve with a legend by plt.legend()

Viewing and saving the figure

plt.savefig('output.png')        #save before show
plt.show()
  • If you want to both view the image on screen and save it in file, remember to call plt.savefig() before plt.show() to make sure you don't save a blank canvas.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,434评论 0 10
  • 最近在看runloop时看到不少blog都说AFNetworking,有使用到runloop创建一个子线程并保持线...
    学习无底阅读 1,399评论 2 12
  • 文/奈么. 红了樱桃,绿了芭蕉。闲暇时间很多。所以我仿了几幅画。也是古戈力的哟! 我用手机上的滤镜过了一下。有质感...
    奈么阅读 252评论 0 0
  • 对于欧洲大陆上的民族,恐怕大家的了解是很少的,甚至有很多人认为生活在欧洲的不都是罗马人吗?实际上不是这样的。 因为...
    机智的小朋同学阅读 2,699评论 0 3
  • 文/岑岚 文章目录:如果时光不记得——目录 这世上总有一人踏着时光来寻你——目录 前情回顾:如果时光不记得(十七)...
    岑岚阅读 984评论 5 12