23

Python 数据科学入门:Matplotlib 基本的自定义

 4 years ago
source link: http://bigdata.51cto.com/art/202003/613369.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在 Matplotlib 教程中,我们将讨论一些可能的图表自定义。 为了开始修改子图,我们必须定义它们。 我们很快会谈论他们,但有两种定义并构造子图的主要方法。 现在,我们只使用其中一个,但我们会很快解释它们。

现在,修改我们的graph_data函数:

def graph_data(stock): 
 
    fig = plt.figure() 
    ax1 = plt.subplot2grid((1,1), (0,0))1234 

为了修改图表,我们需要引用它,所以我们将它存储到变量fig。 然后我们将ax1定义为图表上的子图。 我们在这里使用subplot2grid,这是获取子图的两种主要方法之一。 我们将深入讨论这些东西,但现在,你应该看到我们有 2 个元组,它们提供了(1,1)和(0,0)。 1,1表明这是一个 1×1 网格。 然后0,0表明这个子图的『起点』将为0,0。

接下来,通过我们已经编写的代码来获取和解析数据:

stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv' 
source_code = urllib.request.urlopen(stock_price_url).read().decode() 
stock_data = [] 
split_source = source_code.split('\n') 
for line in split_source: 
    split_line = line.split(',') 
    if len(split_line) == 6: 
        if 'values' not in line and 'labels' not in line: 
            stock_data.append(line) 
 
date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, 
                                                      delimiter=',', 
                                                      unpack=True, 
                                                      converters={0: bytespdate2num('%Y%m%d')})1234567891011121314 

下面,我们这样绘制数据:

ax1.plot_date(date, closep,'-', label='Price')1 

现在,由于我们正在绘制日期,我们可能会发现,如果我们放大,日期会在水平方向上移动。但是,我们可以自定义这些刻度标签,像这样:

for label in ax1.xaxis.get_ticklabels():  
    label.set_rotation(45)12 

这将使标签转动到对角线方向。 接下来,我们可以添加一个网格:

ax1.grid(True)1 

然后,其它东西我们保留默认,但我们也可能需要略微调整绘图,因为日期跑到了图表外面。 记不记得我们在第一篇教程中讨论的configure subplots按钮? 我们不仅可以以这种方式配置图表,我们还可以在代码中配置它们,以下是我们设置这些参数的方式:

plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)1 

现在,为了防止我们把你遗留在某个地方,这里是完整的代码:

import matplotlib.pyplot as plt 
import numpy as np 
import urllib 
import matplotlib.dates as mdates 
 
def bytespdate2num(fmt, encoding='utf-8'): 
    strconverter = mdates.strpdate2num(fmt) 
    def bytesconverter(b): 
        s = b.decode(encoding) 
        return strconverter(s) 
    return bytesconverter 
 
 
def graph_data(stock): 
 
    fig = plt.figure() 
    ax1 = plt.subplot2grid((1,1), (0,0)) 
 
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv' 
    source_code = urllib.request.urlopen(stock_price_url).read().decode() 
    stock_data = [] 
    split_source = source_code.split('\n') 
    for line in split_source: 
        split_line = line.split(',') 
        if len(split_line) == 6: 
            if 'values' not in line and 'labels' not in line: 
                stock_data.append(line) 
 
    date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, 
                                                          delimiter=',', 
                                                          unpack=True, 
                                                          converters={0: bytespdate2num('%Y%m%d')}) 
 
    ax1.plot_date(date, closep,'-', label='Price') 
    for label in ax1.xaxis.get_ticklabels(): 
        label.set_rotation(45) 
    ax1.grid(True)#, color='g', linestyle='-', linewidth=5) 
 
    plt.xlabel('Date') 
    plt.ylabel('Price') 
    plt.title('Interesting Graph\nCheck it out') 
    plt.legend() 
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0) 
    plt.show() 
 
 
graph_data('TSLA')1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 

结果为:

Fr2aInr.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK