Python数据分析三剑客:Pandas、Numpy、Matplotlib我爱编程

Matplotlib:Get_started

2018-08-04  本文已影响13人  ACphart

Loading data for plotting

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)
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

Viewing and saving the figure

plt.savefig('output.png')        #save before show
plt.show()
上一篇 下一篇

猜你喜欢

热点阅读