Python plot charts

Source: Internet
Author: User
Tags unpack

1. Tools

Matplotlib

NumPy

2.matplotlib use

Import Matplotlib.pyplot as Plt #plt用于显示图片
Import Matplotlib.image as Mping #mping用于读取图片
Import datetime as DT
Import Matplotlib.dates as Mdates
From Pylab Import *


def draw_trend_chart (dates,y):
mpl.rcparams[' font.sans-serif '] = [' Simhei '] #指定默认字体
mpl.rcparams[' axes.unicode_minus ' = False #解决保存图像是负号 '-' is displayed as a block problem

x = [Dt.datetime.strptime (d, '%y/%m/%d '). Date () for d in dates]
#plt. Figure (Figsize= (8,8))
Plt.figure ()

#plt. GCA (). Xaxis.set_major_formatter (mdates. Dateformatter ('%m/%d/%y '))
#plt. GCA (). Xaxis.set_major_locator (mdates. Daylocator ())
#plt. Plot (x, y, "r--", linewidth=2)
Plt.plot (x, Y, "R", Linewidth=1)
#plt. GCF (). Autofmt_xdate ()

#plt. Xlabel ("DATE") #x轴标签
Plt.ylabel ("WEIGHT") #y轴标签
Plt.title ("MY Health TRACKING") #标题

Plt.savefig ("Liuyang.png") #保存图片名称

Lena = Mping.imread (' liuyang.png ') #读取图片文件信息
Lena.shape # (512,512,3)

Plt.imshow (Lena) #显示图片
Plt.axis (' off ') #不显示坐标轴
Plt.title ("")
Plt.show () #显示

def get_weight_data (filename):
Time = []
Weight = []
Filecontent=open (filename, "R")
For Eachline in Filecontent:
Eachdata = Eachline.strip (' \ n '). Split (",")
If Eachdata[-1].strip () = = ":
Continue
Else
Time.append (Eachdata[0])
Weight.append (Eachdata[1])
return [Time, weight]

data = Get_weight_data ("Data.csv")
Draw_trend_chart (Data[0],data[1])

3.numpy

. NumPy Arrays
NumPy is a commonly used data processing library, I will be 000001. SZ's stock price data (time range from 20150101 to 20150930) is imported into the CSV and then read by NumPy to get the date and price array. The CSV file contains two columns, date and price, the split symbol is "," and the Read procedure Code is as follows:

Dates, close = Np.loadtxt (filename,delimiter= ",", unpack= True, Converters={0:mdates.strpdate2num ('%y-%m-%d ')})

NumPy's Loadtxt method: Sets the delimiter in the file as ",", unpack whether to split the array, true to split, that is, to get two arrays representing the date and closing price, converters is to convert the date type string into an array, Because numpy specifies that the types in the array need to be consistent.
2. Draw Basic Charts
After the date and closing price is obtained by NumPy, the plot method is used to draw with reference to the previous example:

Ax1.plot (Dates,close)

The chart looks like this:


In, the x-axis is identified by a numeric value, not a date type. Because when we construct an array by NumPy, the date is stored as a numeric type and can be converted to a date type by the following method:

    Ax1.xaxis.set_major_locator (mdates. Daylocator (Bymonthday=range (1,32), interval=15))     Ax1.xaxis.set_major_formatter (mdates. Dateformatter ("%y-%m-%d")) for      label in Ax1.xaxis.get_ticklabels ():          label.set_rotation (45)

The x-axis setting major scale locator is the daily scale, in the format: Dateformatter ("%y-%m-%d"), the daily scale from the 1th day to the 31st day, the interval is 15th. The chart looks like this:

Each of the ticker labels on the x-axis is tilted 45 degrees to the right so that the labels do not overlap together for easy viewing.
can also be displayed monthly, the x-axis set the main scale is the monthly scale, in the format: Dateformatter ("%y-%m"), the conversion code is as follows:

    Ax1.xaxis.set_major_locator (mdates. Monthlocator ())      Ax1.xaxis.set_major_formatter (mdates. Dateformatter ("%y-%m"))

The chart looks like this:


3. Graphics Border Adjustment
The attentive reader may find that the date label at the bottom (bottom) is incomplete. At this point, you can click the "Configure Subplots" button, adjust the left and right borders, and then save. The chart looks like this:

You can also adjust the border by using the Subplots_adjust method:

    Plt.subplots_adjust (bottom=0.13,top=0.95)

4. Draw the price average line
In the previous example, a basic stock chart was drawn, and in this section we draw the price averages for 5th and 10th using the Ta-lib "4" Securities technical Indicator Library.
The method Talib is provided in the ta-lib. SMA gets the price simple average line, timeperiod for the time parameter, timeperiod=5 for the 5th EMA, based on the increase of 5th and 10th EMA, code as follows:

    SMA5 = Talib.sma (Close, timeperiod = 5)      ax1.plot (dates,sma5)      sma10 = Talib.sma (Close, timeperiod = ten)      Ax1.plot (DATES,SMA10)

Of these, SMA5 and sma10 are numpy arrays.
The chart looks like this:

There are three curves in the axis, Matplotlib will automatically change the line color, if not described is not convenient to use, you can add a legend in the upper right corner, indicating the meaning of the lines, and increase the grid effect of the chart, the code is as follows:

Plt.legend ((' Daily ', ' SMA5 ', ' SMA10 '))  Plt.grid (True)

The chart looks like this:

4.http://www.cnblogs.com/bradleon/p/6832867.html

Python plot charts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.