python數(shù)據(jù)分析(十)

# -*- coding: utf-8 -*-

from __future__ import division

from numpy.random import randn

import numpy as np

import os

import matplotlib.pyplot as plt

np.random.seed(12345)

plt.rc('figure', figsize=(10, 6))

from pandas import Series, DataFrame

import pandas as pd

np.set_printoptions(precision=4)

get_ipython().magic(u'matplotlib inline')

get_ipython().magic(u'pwd')

#####matplotlib創(chuàng)建圖表

plt.plot([1,2,3,2,3,2,2,1])

plt.show()

plt.plot([4,3,2,1],[1,2,3,4])

plt.show()

#更多簡單的圖形

x = [1,2,3,4]

y = [5,4,3,2]

plt.figure()

plt.subplot(2,3,1)

plt.plot(x, y)

plt.subplot(232)

plt.bar(x, y)

plt.subplot(233)

plt.barh(x, y)

plt.subplot(234)

plt.bar(x, y)

y1 = [7,8,5,3]

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

plt.subplot(235)

plt.boxplot(x)

plt.subplot(236)

plt.scatter(x,y)

plt.show()

#####figure與subplot

#figure對象

fig = plt.figure()

ax1 = fig.add_subplot(2, 2, 1)

ax2 = fig.add_subplot(2, 2, 2)

ax3 = fig.add_subplot(2, 2, 3)

plt.show()

from numpy.random import randn

plt.plot(randn(50).cumsum(), 'k--')

fig.show()

_ = ax1.hist(randn(100), bins=20, color='k', alpha=0.3)

ax2.scatter(np.arange(30), np.arange(30) + 3 * randn(30))

plt.close('all')

fig, axes = plt.subplots(2, 3)

axes

#調(diào)整subplot周圍的間距

plt.subplots_adjust(left=None, bottom=None, right=None, top=None,

wspace=None, hspace=None)

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)

for i in range(2):

for j in range(2):

axes[i, j].hist(randn(500), bins=50, color='k', alpha=0.5)

plt.subplots_adjust(wspace=0, hspace=0)

#####matplotlib基本設(shè)置

#顏色、標(biāo)記和線型

plt.figure()

plt.plot(x,y,linestyle='--',color='g')

plt.plot(randn(30).cumsum(), 'ko--')

plt.plot(randn(30).cumsum(),color='k',linestyle='dashed',marker='o')

plt.close('all')

data = randn(30).cumsum()

plt.plot(data, 'k--', label='Default')

plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')

plt.legend(loc='best')

#設(shè)置標(biāo)題诈胜、軸標(biāo)簽财饥、刻度以及刻度標(biāo)簽

fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)

ax.plot(randn(1000).cumsum())

ticks = ax.set_xticks([0, 250, 500, 750, 1000])

labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],

rotation=30, fontsize='small')

ax.set_title('My first matplotlib plot')

ax.set_xlabel('Stages')

#添加圖例

fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)

ax.plot(randn(1000).cumsum(), 'k', label='one')

ax.plot(randn(1000).cumsum(), 'k--', label='two')

ax.plot(randn(1000).cumsum(), 'k.', label='three')

ax.legend(loc='best')

#注釋以及在subplot上繪圖

from datetime import datetime

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

data = pd.read_csv('d:/data/spx.csv', index_col=0, parse_dates=True)

spx = data['SPX']

spx.plot(ax=ax, style='k-')

crisis_data = [

(datetime(2007, 10, 11), 'Peak of bull market'),

(datetime(2008, 3, 12), 'Bear Stearns Fails'),

(datetime(2008, 9, 15), 'Lehman Bankruptcy')

]

for date, label in crisis_data:

ax.annotate(label, xy=(date, spx.asof(date) + 50),

xytext=(date, spx.asof(date) + 200),

arrowprops=dict(facecolor='black'),

horizontalalignment='left', verticalalignment='top')

ax.set_xlim(['1/1/2007', '1/1/2011'])

ax.set_ylim([600, 1800])

ax.set_title('Important dates in 2008-2009 financial crisis')

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)

circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)

pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],

color='g', alpha=0.5)

ax.add_patch(rect)

ax.add_patch(circ)

ax.add_patch(pgon)

#圖表的保存

fig

fig.savefig('figpath.svg')

fig.savefig('figpath.png', dpi=400, bbox_inches='tight')

from io import BytesIO

buffer = BytesIO()

plt.savefig(buffer)

plot_data = buffer.getvalue()

#matplotlib配置

plt.rc('figure', figsize=(10, 10))

font_options={'family':'monospace',

'weight':'bold','size':'small'}

plt.rc('font',**font_options)

#####pandas中的繪圖函數(shù)

#線圖

plt.close('all')

s = Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))

s.plot()

df = DataFrame(np.random.randn(10, 4).cumsum(0),

columns=['A', 'B', 'C', 'D'],

index=np.arange(0, 100, 10))

df.plot()

#柱形圖

fig, axes = plt.subplots(2, 1)

data = Series(np.random.rand(16), index=list('abcdefghijklmnop'))

data.plot(kind='bar', ax=axes[0], color='k', alpha=0.7)

data.plot(kind='barh', ax=axes[1], color='k', alpha=0.7)

df = DataFrame(np.random.rand(6, 4),

index=['one', 'two', 'three', 'four', 'five', 'six'],

columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))

df

df.plot(kind='bar')

plt.figure()

df.plot(kind='barh', stacked=True, alpha=0.5)

tips = pd.read_csv('d:/data/tips.csv')

party_counts = pd.crosstab(tips.day, tips['size'])

party_counts

party_counts = party_counts.ix[:, 2:5]

party_pcts = party_counts.div(party_counts.sum(1).astype(float), axis=0)

party_pcts

party_pcts.plot(kind='bar', stacked=True)

#直方圖和密度圖

plt.figure()

tips['tip_pct'] = tips['tip'] / tips['total_bill']

tips['tip_pct'].hist(bins=50)

plt.figure()

tips['tip_pct'].plot(kind='kde')

plt.figure()

comp1 = np.random.normal(0, 1, size=200) ?# N(0, 1)

comp2 = np.random.normal(10, 2, size=200) ?# N(10, 4)

values = Series(np.concatenate([comp1, comp2]))

values.hist(bins=100, alpha=0.3, color='k', normed=True)

values.plot(kind='kde', style='k--')

#散點(diǎn)圖

macro = pd.read_csv('d:/data/macrodata.csv')

data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]

trans_data = np.log(data).diff().dropna()

trans_data[-5:]

plt.figure()

plt.scatter(trans_data['m1'], trans_data['unemp'])

plt.title('Changes in log %s vs. log %s' % ('m1', 'unemp'))

pd.scatter_matrix(trans_data, diagonal='kde', color='k', alpha=0.3)

#####Matplotlib作圖

#誤差條形圖

x = np.arange(0, 10, 1)

y = np.log(x)

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

plt.bar(x, y, yerr=xe, width=0.4, align='center', ecolor='r', color='cyan',

label='experiment #1');

plt.xlabel('# measurement')

plt.ylabel('Measured values')

plt.title('Measurements')

plt.legend(loc='upper left')

plt.show()

#餅圖

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]

plt.pie(values, explode=explode, labels=labels,

autopct='%1.1f%%', startangle=67)

plt.title('Rainy days by season')

plt.show()

#等高線圖

import matplotlib as mpl

def process_signals(x, y):

return (1 - (x ** 2 + y ** 2)) * np.exp(-y ** 3 / 3)

x = np.arange(-1.5, 1.5, 0.1)

y = np.arange(-1.5, 1.5, 0.1)

X, Y = np.meshgrid(x, y)

Z = process_signals(X, Y)

N = np.arange(-1, 1.5, 0.3)

CS = plt.contour(Z, N, linewidths=2, cmap=mpl.cm.jet)

plt.clabel(CS, inline=True, fmt='%1.1f', fontsize=10)

plt.colorbar(CS)

plt.title('My function: $z=(1-x^2+y^2) e^{-(y^3)/3}$')

plt.show()

###3D圖像

#3d柱形圖

import matplotlib.dates as mdates

from mpl_toolkits.mplot3d import Axes3D

mpl.rcParams['font.size'] = 10

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

for z in [2011, 2012, 2013, 2014]:

xs = xrange(1,13)

ys = 1000 * np.random.rand(12)

color = plt.cm.Set2(random.choice(xrange(plt.cm.Set2.N)))

ax.bar(xs, ys, zs=z, zdir='y', color=color, alpha=0.8)

ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))

ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))

ax.set_xlabel('Month')

ax.set_ylabel('Year')

ax.set_zlabel('Sales Net [usd]')

plt.show()

#3d直方圖

mpl.rcParams['font.size'] = 10

samples = 25

x = np.random.normal(5, 1, samples)

y = np.random.normal(3, .5, samples)

fig = plt.figure()

ax = fig.add_subplot(211, projection='3d')

hist, xedges, yedges = np.histogram2d(x, y, bins=10)

elements = (len(xedges) - 1) * (len(yedges) - 1)

xpos, ypos = np.meshgrid(xedges[:-1]+.25, yedges[:-1]+.25)

xpos = xpos.flatten()

ypos = ypos.flatten()

zpos = np.zeros(elements)

dx = .1 * np.ones_like(zpos)

dy = dx.copy()

dz = hist.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', alpha=0.4)

ax.set_xlabel('X Axis')

ax.set_ylabel('Y Axis')

ax.set_zlabel('Z Axis')

ax2 = fig.add_subplot(212)

ax2.scatter(x, y)

ax2.set_xlabel('X Axis')

ax2.set_ylabel('Y Axis')

plt.show()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末躯砰,一起剝皮案震驚了整個濱河市淑际,隨后出現(xiàn)的幾起案子晚树,更是在濱河造成了極大的恐慌译秦,老刑警劉巖两残,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異委刘,居然都是意外死亡丧没,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門锡移,熙熙樓的掌柜王于貴愁眉苦臉地迎上來呕童,“玉大人,你說我怎么就攤上這事淆珊《崴牵” “怎么了?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵套蒂,是天一觀的道長钞支。 經(jīng)常有香客問我,道長操刀,這世上最難降的妖魔是什么烁挟? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮骨坑,結(jié)果婚禮上撼嗓,老公的妹妹穿的比我還像新娘。我一直安慰自己欢唾,他們只是感情好且警,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著礁遣,像睡著了一般斑芜。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上祟霍,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天杏头,我揣著相機(jī)與錄音盈包,去河邊找鬼。 笑死醇王,一個胖子當(dāng)著我的面吹牛呢燥,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播寓娩,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼叛氨,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了棘伴?” 一聲冷哼從身側(cè)響起寞埠,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎排嫌,沒想到半個月后畸裳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淳地,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了帅容。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片颇象。...
    茶點(diǎn)故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖并徘,靈堂內(nèi)的尸體忽然破棺而出遣钳,到底是詐尸還是另有隱情,我是刑警寧澤麦乞,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布蕴茴,位于F島的核電站,受9級特大地震影響姐直,放射性物質(zhì)發(fā)生泄漏倦淀。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一声畏、第九天 我趴在偏房一處隱蔽的房頂上張望撞叽。 院中可真熱鬧,春花似錦插龄、人聲如沸愿棋。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽糠雨。三九已至,卻和暖如春徘跪,著一層夾襖步出監(jiān)牢的瞬間甘邀,已是汗流浹背砂竖。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鹃答,地道東北人乎澄。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像测摔,于是被迫代替她去往敵國和親置济。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容