python数据处理3

2019-08-01  本文已影响0人  无涯2016

------------------------------------------------------------------

#========================================================

#第3章 绘制并定制化图表 65

#========================================================

3.1 简介 65

#==============================================================================

# 3.2 定义图表类型——柱状图、线形图和堆积柱状图 66

#==============================================================================

3.2.1 准备工作 66

3.2.2 操作步骤 66

3.2.3 工作原理 69

3.2.4 补充说明 70

from matplotlib.pyplot import *

x = [1,2,3,4]; y = [5,4,3,2]

figure()

subplot(231)

plot(x, y)

subplot(232)

bar(x, y)

#horizontal bar-charts

subplot(233)

barh(x, y)

#stacked bar-charts

subplot(234)

bar(x, y)

y1 = [7,8,5,3]

bar(x, y1, bottom=y, color = 'r')

subplot(235)

boxplot(x)

subplot(236)

scatter(x,y)

show()

'''

同一个箱线图可以显示五种数据:

最小值

最大值

中值

第二四分位数:其以下数据集合中较低的25%的数据

第三四分位数:其以上数据集合中较高的25%的数据

from pylab import *

dataset = [113, 115, 119, 121, 124,

  124, 125, 126, 126, 126,

  127, 127, 128, 129, 130,

  130, 131, 132, 133, 136]

subplot(121)

boxplot(dataset, vert=False)

subplot(122)

hist(dataset)

show()

#========================================================

#3.3 简单的正弦图和余弦图 71

#========================================================

3.3.1 准备工作 71

3.3.2 操作步骤 71

from pylab import *

import numpy as np

# generate uniformly distributed

# 256 points from -pi to pi, inclusive

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)

y = np.cos(x)

plot(x, y)

y1 = np.sin(x)

plot(x, y1)

title("Functions $\sin$ and $\cos$")

xlim(-3.0, 3.0)# set x limit

ylim(-1.0, 1.0)# set y limit

# format ticks at specific values

xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],  [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

yticks([-1, 0, +1],  [r'$-1$', r'$0$', r'$+1$'])

show()

#==============================================================================

# 3.4 设置坐标轴长度和范围 74

#==============================================================================

3.4.1 准备工作 74

3.4.2 操作步骤 74

3.4.3 工作原理 74

3.4.4 补充说明 76

from pylab import *

axis()  #0.0,1.0,0.0,1.0

#添加新的坐标轴

axis([-1,1,-10,10])

axhline()  #绘制y=0的线

axvline()  #绘制x=0的线

axhline(4)  #绘制y=4

#grid()

grid(which=u'both',axis=u'both')

#==============================================================================

# 3.5 设置图表的线型、属性和格式化字符串 76

#==============================================================================

3.5.1准备工作 77

3.5.2 操作步骤 77

3.5.3 工作原理 77

import numpy as np

x = np.arange(0,4*math.pi,0.1)

y = sin(x)

#或者 plot(x,y,linewidth=1.5)

#或者 line = plot(x,y,linewidth=1.5)

#或者

lines = plot(x,y)

#setp(lines,marker=7)

setp(lines,alpha=1)

'''

'b':蓝

'g':绿

'r':红

'c'

'm':

'y':黄

'k':黑

'w':白

'''

setp(lines,color='r')

setp(lines,color='#eeefff')

setp(lines,color=[0.3,0.3,0.3])

#setp(lines,dashes=[1,1]) #数组为序列各段的宽度,

'''

-  :实线

-- :破折线

-. :点划线

'''

setp(lines,linestyle='--')

setp(lines,label='das')

setp(lines,'linewidth',1.5)

setp(lines,linewidth=1.5)

setp(lines,lw=1.5)

'''线条标记

'o':圆圈

'D':菱形

'd':小菱形

'h':六边形

'H':六边形

'_':水平线

'',' ','None',None:无

'8':八边形

'p':五边形

',':像素

'+'

'.':

's':正方形

'*':

'v':三角形

'<':三角形

'>':三角形

'^':三角形

'|':竖线

'x':

'''

setp(lines,marker=',')

#标记边缘宽度

setp(lines,markeredgewidth=1)

setp(lines,mew=1)

#标记的边缘颜色

setp(lines,markeredgecolor='g')

setp(lines,mec='g')

#标记颜色

setp(lines,markerfacecolor='g')

setp(lines,mfc='g')

#subplot(111,axisbg=(0.1843,0.3098,0.3098))

#==============================================================================

# 3.6 设置刻度、刻度标签和网格 80

#==============================================================================

3.6.1 准备工作 80

3.6.2 操作步骤 81

from pylab import *

import matplotlib as mpl

import datetime

fig = figure()

ax = gca()# get current axis

# set some daterange

start = datetime.datetime(2013, 01, 01)

stop = datetime.datetime(2013, 12, 31)

delta = datetime.timedelta(days = 1)

dates = mpl.dates.drange(start, stop, delta) # convert dates for matplotlib

values = np.random.rand(len(dates))# generate some random values

ax = gca()

ax.plot_date(dates, values, linestyle='-', marker='')# create plot with dates

date_format = mpl.dates.DateFormatter('%Y-%m-%d')# specify formater

ax.xaxis.set_major_formatter(date_format)# apply formater

# autoformat date labels

# rotates labels by 30 degrees by default

# use rotate param to specify different rotation degree

# use bottom param to give more room to date labels

fig.autofmt_xdate()

show()

#==============================================================================

# 3.7 添加图例和注解 83

#==============================================================================

3.7.1 准备工作 84

3.7.2 操作步骤 84

3.7.3 工作原理 85

from matplotlib.pyplot import *

# generate different normal distributions

x1 = np.random.normal(30, 3, 100)

x2 = np.random.normal(20, 2, 100)

x3 = np.random.normal(10, 3, 100)

# plot them

plot(x1, label='plot')

plot(x2, label='2nd plot')

plot(x3, label='last plot')

# generate a legend box

legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.)

# annotate an important value

annotate("Important value", (55,20), xycoords='data', xytext=(5,38), arrowprops=dict(arrowstyle='->'))

show()

#==============================================================================

# 3.8 移动轴线到图中央 86

#==============================================================================

3.8.1 操作步骤 86

3.8.2 工作原理 87

3.8.3 补充说明 87

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(-np.pi, np.pi, 500, endpoint=True)

y = np.sin(x)

plt.plot(x, y)

ax = plt.gca()

# hide two spines

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

# move bottom and left spine to 0,0

ax.spines['bottom'].set_position(('data',0))

ax.spines['left'].set_position(('data',0))

# move ticks positions

ax.xaxis.set_ticks_position('bottom')

ax.yaxis.set_ticks_position('left')

plt.show()

#==============================================================================

# 3.9 绘制直方图 87

#==============================================================================

3.9.1 准备工作 88

3.9.2 操作步骤 88

3.9.3 工作原理 90

import numpy as np

import matplotlib.pyplot as plt

mu = 100

sigma = 15

x = np.random.normal(mu, sigma, 10000)

ax = plt.gca()

# the histogram of the data

'''相关参数

bins:

range:bin的范围

normed:若为True,直方图的值将进行归一化,形成概率密度

histtype:

    barstacked

    step

    stepfilled

align:

color:

orientation:

    orientation

    horizontal

'''

ax.hist(x, bins=35, color='r',normed=True,histtype='stepfilled')

ax.set_xlabel('Values')

ax.set_ylabel('Frequency')

ax.set_title(r'$\mathrm{Histogram:}\ \mu=%d,\ \sigma=%d$' % (mu, sigma))

plt.show()

#==============================================================================

# 3.10 绘制误差条形图 90

#==============================================================================

3.10.1 准备工作 90

3.10.2 操作步骤 90

3.10.3 工作原理 91

3.10.4 补充说明 92

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 10, 1)# generate measures from gaussian distribution

y = np.log(x) # values computed from "measured"

# add some error samples from standard normal distribution

xe = 0.1 * np.abs(np.random.randn(len(y)))

'''# draw and show errorbar

width

bottom:柱状图的初始高度

edgecolor:误差条边界颜色

ecolor:误差条颜色

linewidth

orientation:vertical,horizontal

xerr,yerr:在柱状图上生成误差条

'''

plt.bar(x, y, yerr=xe, width=0.4, align='center', ecolor='r', color='cyan',label='experiment #1');

# give some explainations

plt.xlabel('# measurement')

plt.ylabel('Measured values')

plt.title('Measurements')

plt.legend(loc='upper left')

plt.show()

#==============================================================================

# 3.11 绘制饼图 92

#==============================================================================

3.11.1 准备工作 92

3.11.2 操作步骤 93

import matplotlib.pyplot as plt

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

ax = plt.axes([0.1, 0.1, 0.8, 0.8])

labels = 'Spring', 'Summer', 'Autumn', 'Winter'

values = [15, 16, 16, 28]

explode =[0.1, 0.1, 0.1, 0.1]

'''

startangle:

    0 :扇区将从x轴开始逆时针排列;

    90:从y轴开始逆时针排列

'''

plt.pie(values, explode=explode, labels=labels,  autopct='%1.1f%%', startangle=90)

plt.title('Rainy days by season')

plt.show()

#==============================================================================

# 3.12 绘制带填充区域的图表 94

#==============================================================================

3.12.1 准备工作 94

3.12.2 操作步骤 94

3.12.3 工作原理 95

3.12.4 补充说明 96

from matplotlib.pyplot import figure, show, gca

import numpy as np

x = np.arange(0.0, 2, 0.01)

y1 = np.sin(2*np.pi*x)

y2 = 1.2*np.sin(4*np.pi*x)

fig = figure()

ax = gca()

ax.plot(x, y1, x, y2, color='black')

ax.fill_between(x, y1, y2, where=y2>=y1, facecolor='darkblue', interpolate=True)

ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='deeppink', interpolate=True)

#针对水平曲线 ax.fill_betweenx()

#ax.fill_betweenx()

#fill 对任意多边形填充颜色或者阴影线

ax.set_title('filled between')

show()

#==============================================================================

# 3.13 绘制带彩色标记的散点图 96

#==============================================================================

3.13.1 准备工作 96

3.13.2 操作步骤 96

3.13.3 工作原理 98

import numpy as np

import matplotlib.pyplot as plt

mu = 100

sigma = 15

x = np.random.normal(mu, sigma, 10000)

ax = plt.gca()

# the histogram of the data

'''相关参数

bins:

range:bin的范围

normed:若为True,直方图的值将进行归一化,形成概率密度

histtype:

    barstacked

    step

    stepfilled

align:

color:

orientation:

    orientation

    horizontal

'''

ax.hist(x, bins=35, color='r',normed=True,histtype='stepfilled')

ax.set_xlabel('Values')

ax.set_ylabel('Frequency')

ax.set_title(r'$\mathrm{Histogram:}\ \mu=%d,\ \sigma=%d$' % (mu, sigma))

plt.show()

上一篇下一篇

猜你喜欢

热点阅读