Matplotlib畫圖

Matplotlib

Matplotlib基本

在這裏插入圖片描述

########################################
####                                ####
####           Matplotlib           ####
####                                ####
########################################
from __future__ import division
import numpy as np
import pandas as pd
from pandas import DataFrame,Series
import os
import matplotlib.pyplot as plt
###matplotlib創建圖表
plt.plot([1, 2, 3, 2, 3, 2, 2, 1])
plt.show()
##前面的y軸,後面的是x軸
plt.plot([4,3,2,1],[1,2,3,4])
plt.show()
x = [1,2,3,4]
y = [5,4,3,2]
#畫多個圖
plt.figure()
#分成2 * 3個區域,畫第1個上面
#線性圖
plt.subplot(231)
plt.plot(x,y)
#筒形圖
plt.subplot(232)
plt.bar(x,y)
#筒形圖(和上面x,y相反)
plt.subplot(233)
plt.bar(x,y)
#筒形圖(兩個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()

plt.show()

####figure與subpolt
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)
#cumsum() 累加,第一個元素加到第二個,在累加到第三個 k--黑色的曲線
plt.plot(np.random.randn(50).cumsum(),'k--')
#在第一個格子裏面繪圖 直方圖  間距(劃分成多少快) 顏色的深度
ax1.hist(np.random.randn(100),bins=20,color='r',alpha=1)
#散點圖
ax2.scatter(np.arange(30),np.arange(30)+np.random.randn(30)*3)
plt.show()
plt.close()

fig,axes = plt.subplots(2,3)
axes[0][0].scatter(np.arange(30),np.arange(30)+np.random.randn(30)*3)
plt.show()

plt.subplots_adjust(None,None,None,None,None,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(np.random.randn(500),bins=50,color='r',alpha=1)
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()

#####matplotlib基本設置
#顏色,標記和線型
plt.figure()
x = [1, 2, 3, 4]
y = [5, 4, 3, 2]
# b--顏色和虛線
plt.plot(x,y,'r--')
plt.plot(x,y,linestyle="--",color='r')
# k = 黑色 o = 標記 -- 虛線
data = np.random.randn(30).cumsum()
plt.plot(data, 'ko--')
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='step-post')
plt.legend(loc='best')
plt.show()
plt.close("all")
######設置標題、軸標籤、刻度以及刻度標籤
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.randn(1000).cumsum())
#設置下標
ax.set_xticks([0, 250, 500, 750, 1000])
# rotation旋轉角度,fontsize字體大小
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
                   rotation=30, fontsize='small')
#圖名字
ax.set_title("My First Matplotlib Plot")
#y軸標籤
ax.set_ylabel("y")
#x軸標籤
ax.set_xlabel("x")
plt.show()


###添加圖例
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.randn(1000).cumsum(),'k', label='one')
ax.plot(np.random.randn(1000).cumsum(),'k--', label='two')
ax.plot(np.random.randn(1000).cumsum(),'k.', label='three')
#在圖上添加label標籤
#   如  ——— one
#       - - two
#       · · three
plt.legend(loc='best')
plt.show()

#註釋以及在subplot上繪圖
from datetime import datetime
fig = plt.figure()
ax = fig.add_subplot(111)
#使用第一列當成索引並解析
data = pd.read_csv("week7/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_title("Imprtana dates in 2008-2009 financial crisis")
plt.show()

Pandas中的基本圖形

在這裏插入圖片描述

#########pandas中的繪圖函數
s = Series(np.random.randn(10),index=np.arange(0,100,10))
s.plot()
plt.show()

df = DataFrame(np.random.randn(10,4).cumsum(0),
               columns=['A','B','C','D'],
               index=np.arange(0,100,10))
df.plot()
plt.show()

fig,axes = plt.subplots(2,1)
data = Series(np.random.randn(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)
plt.show()

df = DataFrame(np.random.randn(6,4),
               index=['one','tow','three','four','five','six'],
               columns=pd.Index(['A','B','C','D'],name='Genus'))
#df.plot(kind='bar')
#plt.figure()
#df.plot(kind='barh',stacked=True,alpha=0.5)
#plt.show()

tips = pd.read_csv('week7/tips.csv')
#統計 類似與groupBy
party_counts = pd.crosstab(tips.day,tips['size'])
#統計比較多的2345
party_counts = party_counts.loc[:,2:5]
print(party_counts)
#轉換成百分比形式
#按照 彙總和進行相除
party_pcts = party_counts.div(party_counts.sum(1).astype(float),axis=0)
# print(party_counts.sum(1))
# print(party_pcts)
party_pcts.plot(kind='bar',stacked=True)
#plt.show()
##直方圖和密度圖
tips = pd.read_csv('week7/tips.csv')
print(tips)
tips['tip_pct'] = tips['tip'] / tips['total_bill']
tips['tip_pct'].hist(bins=50)
plt.show()
#正態分佈
comp1 = np.random.normal(0,1,size=200)
comp2 = np.random.normal(10,2,size=200)
#數值組合
values = Series(np.concatenate([comp1,comp2]))
values.hist(bins=100,alpha=0.3,color='k',density=True)
values.plot(kind='kde',style='k--')
plt.show()

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',color='cyan',ecolor='r',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))
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=0)       #旋轉多少度
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)
process_signals(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.show()

在這裏插入圖片描述

3D柱形圖

###3D柱形圖
import matplotlib as mpl
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 = range(1,13)
    ys = 1000 * np.random.rand(12)
    color = plt.cm.Set2(np.random.choice(range(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直方圖

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

在這裏插入圖片描述

發佈了143 篇原創文章 · 獲贊 40 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章