python数据处理3

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

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

#第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()

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容