import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns
matplotlib參數設置
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] matplotlib.rcParams['font.family']='sans-serif' matplotlib.rcParams['axes.unicode_minus'] = False #matplotlib.fontsize='15' #plt.rcParams['figure.figsize'] = (12.0,5.0) #設置圖形大小 #圖形內嵌式,notebook模式下(注釋不可加在下列命令后) %matplotlib inline #ipython模式下 #%pylab inline
seaborn參數設置
#Seaborn有兩組函數對風格進行控制:axes_style()/set_style()函數和plotting_context()/set_context()函數。
#Seaborn有5種預定義的主題:darkgrid(默認)、whitegrid、dark、white、ticks
#Seaborn有4種預定義的上下文:paper、notebook(默認)、talk、poster
sns.set_style("whitegrid")
'''
sns.set_context("poster")
sns.set_style(style=None, rc=None)
sns.despine(offset=10) #圖與軸線距離
sns.despine() #去除刻度和軸線
sns.set_context(fontscale=1.5) #字體大小
sns.set_context(rc={'lines.linewidth':1.5) #線寬
sns.set() #恢復默認值
'''
其他參數設置
myfont = matplotlib.font_manager.FontProperties(fname="simsun.ttc") #自定義字體庫simsun.ttc
ax1.set_xlabel('時間', fontproperties=myfont, size=18) #原始matplotlib不支持中文
plt.gcf().set_facecolor(np.ones(3) * 240/255) #設置背景色
plt.gcf().autofmt_xdate() #自動適應刻度線密度,包括x軸,y軸
plt.legend(loc=1) #1,2,3,4分別對應圖像的右上角,左上角,左下角,右下角
ax.invert_xaxis() #將x軸逆序
線圖(1)
#數據
x=np.linspace(0,10,1000)
y1=np.sin(x)
y2=np.cos(x)
y3=np.cos(x**2)
plt.figure(1) #圖編號
plt.subplot(221)
plt.plot(x,y1,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,y2,label="$cos(x)$",color="blue",linewidth=2)
plt.subplot(222)
plt.scatter(x[:1000:50],y2[:1000:50],color="blue",label="$cos(x^2)$")
plt.subplot(212) #改變圖分塊
plt.plot(x,y1+y3,"g-",label="$sin(x)+cos(x^2)$")
plt.xlabel("time")
plt.ylabel("value")
plt.title("$sin(x)+cos(x^2)$ curve")
plt.xlim(-0.2,10.2)
plt.legend()#顯示左下角的圖例
plt.subplots_adjust(left=0.08,right=0.95,wspace=0.25,hspace=0.45)
#subplots_adjust類似於網頁css格式化中的邊距處理,取決於你需要繪制的大小和各模塊之間的間距
plt.show()

線圖(2)
plt.figure(3)
plt.rcParams['figure.figsize'] = (12,4)
plt.subplot(121)
def sinplot(flip=1):
x=np.linspace(0,14,100)
for i in range(1,7):
plt.plot(x,np.sin(x+i*0.5)*(7-i)*flip)
sinplot()
plt.subplot(122)
x = np.arange(0, 2*np.pi, 0.02)
y = np.sin(x)
y1 = np.sin(2*x)
y2 = np.sin(3*x)
ym1 = np.ma.masked_where(y1 > 0.5, y1)
ym2 = np.ma.masked_where(y2 < -0.5, y2)
#繪圖
lines = plt.plot(x, y, x, ym1, x, ym2, 'o')
#設置線的屬性
plt.setp(lines[0], linewidth=1)
plt.setp(lines[1], linewidth=2)
plt.setp(lines[2], linestyle='-',marker='^',markersize=2)
#線的標簽
plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right')
plt.title('Masked line demo')
plt.show()

條形圖+餅圖+直方圖+階梯圖
plt.figure(2)
#數據
np.random.seed(sum(map(ord,"aesthetics")))
d1 = dict([['A',5], ['B',7], ['C',3]])
d2 = np.random.randn(1000)
#條形圖
plt.subplot(221)
plt.bar(d1.keys(),d1.values(),align='center') #,alpha=.7,color='g'
#plt.bar(range(3),d1.values(),align='center')
#plt.xticks(range(3),xticks)
plt.ylabel("Frequency")
plt.title("Numbers of Books Students Read")
#餅圖
plt.subplot(222)
plt.pie(d1.values(),labels=d1.keys(),autopct='%1.1f%%')
plt.title("Number of Books Students Read")
#直方圖
plt.subplot(223)
plt.hist(d2,100)
plt.xlabel('Heights')
plt.ylabel('Frequency')
plt.title('Height of Students')
#階梯曲線/累積分布曲線
plt.subplot(224)
plt.hist(d2,20,normed=True,histtype='step',cumulative=True)
plt.xlabel('Heights')
plt.ylabel('Frequency')
plt.title('Heights of Students')
plt.subplots_adjust(left=0.08,right=0.95,wspace=0.25,hspace=0.45) #圖間距
plt.show()

餅圖+箱線圖
plt.figure(2)
plt.subplot(121) #fig, ax
animals = dict([['frogs',15], ['hogs',20], ['dogs',45],['cats',10]])
colors = 'yellowgreen','gold','lightskyblue','lightcoral'
explode = 0,0.1,0,0
plt.pie(animals.values(), explode=explode, labels=animals.keys(),
colors=colors, autopct='%1.1f%%', shadow=True, startangle=50) #ax.pie
#ax.set(aspect="equal", title='Pie plot with animals')
plt.axis('equal')
plt.subplot(122)
plt.boxplot(animals.values(),labels=['animals'])
#plt.boxplot((x,y,z),labels=('x','y','z')) #水平vert=False,whis=1.5
#df.boxplot()
plt.title('Heights of Students')
plt.show()

plt.figure(figsize=(12,4), facecolor="white")
#數據
labels=np.array(['綜合', '第一周','第二周','第三周', '第四周', '第五周']) #標簽
nAttr = 6 #數據點個數
values = np.array([88.7, 85, 90, 95, 70, 96]) #原始數據
angles = np.linspace(0,2*np.pi, nAttr, endpoint=False) #弧度
#首尾相連
values = np.concatenate((values,[values[0]]))
angles = np.concatenate((angles,[angles[0]]))
#繪圖
plt.subplot(121, polar=True) #極坐標系
plt.plot(angles, values, 'bo-', color='g', linewidth=2) #線
plt.fill(angles, values, facecolor='g', alpha=0.2) #區域
plt.thetagrids(angles*180/np.pi, labels) #標簽
#plt.figtext(0.52, 0.95, 'python成績分析圖', ha='center') #標題
plt.title('python成績分析圖')
plt.grid(True)
#plt.savefig('dota_radar.JPG')
plt.subplot(122)
#fig, ax = plt.subplots()
vals1 = [1, 2, 3, 4]
vals2 = [2, 3, 4, 5]
vals3=[1]
labels = 'A', 'B', 'C', 'D'
plt.pie(vals1, radius=1.2, autopct='%1.1f%%', pctdistance=0.9)
plt.pie(vals2, radius=1, autopct='%1.1f%%', pctdistance=0.75)
plt.pie(vals3, radius=0.6, colors='w')
#ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.title('Pie plot with xx')
plt.legend(labels, loc='best') #bbox_to_anchor=(1, 1), loc='best', borderaxespad=0.
plt.show()

散點圖+直方圖
plt.figure(figsize=(12,4))
#散點圖
plt.subplot(121)
import matplotlib.cm as cm
def scatter_plot_by_category(feat, x, y):
gs = df.groupby(feat)
cs = cm.rainbow(np.linspace(0, 1, len(gs)))
for g, c in zip(gs, cs):
plt.scatter(g[1][x], g[1][y], color=c, alpha=0.5)
scatter_plot_by_category('target', 'sepal length (cm)', 'sepal width (cm)')
plt.xlabel('sepal length (cm)')
plt.ylabel('sepal width (cm)')
plt.title('target')
#直方圖
plt.subplot(122)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
x1 = np.linspace(x.min(), x.max(), 1000)
normal = mlab.normpdf(x1, mu, sigma) #生成正態曲線的數據
kde = mlab.GaussianKDE(x) #生成核密度曲線的數據
#color='steelblue'
#bins=np.arange(x.min(),x.max(), 5)
#normed=True, #頻率直方圖
#cumulative=True, #積累直方圖
n, bins, patches = plt.hist(x, bins=50, density=1, edgecolor ='k', facecolor='g', alpha=0.75) #邊界色 + 填充色
line1, = plt.plot(x1, normal, 'r-', linewidth = 2)
line2, = plt.plot(x1, kde(x1), 'g-', linewidth = 2)
plt.legend([line1, line2],[ '正態曲線', '核密度曲線'],loc= 'best')
plt.tick_params(top= 'off', right= 'off') #去除邊界刻度
plt.axvline(90) #參考線
plt.text(60, .025, r'$\mu=100,\ \sigma=15$') #文本
plt.axis([40, 160, 0, 0.03]) #刻度區間
plt.grid(ls='--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.show()

seaborn.barplot繪制柱狀圖 更多:Seaborn常見繪圖總結
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(12,4))
plt.subplot(121)
a=np.arange(40).reshape(10,4)
df=pd.DataFrame(a,columns=['a','b','c','d'])
df['a']=[0,4,4,8,8,8,4,12,12,12]
df['d']=list('aabbabbbab')
sns.barplot(x='a', y='b', data=df, hue='d') #分類柱狀圖
plt.subplot(122)
plt.bar(df['a'], df['b'], label='b')
#barh(x,y)
plt.bar(df['a'], df['c'], bottom=df['b'], color='r', label='c')
plt.legend(loc=2)
plt.show()

並列柱狀圖
bar_width = 0.3
x = np.arange(3)
tick_label = ['一級醫院','二級醫院','三級醫院']
plt.figure(figsize=(12,4))
plt.subplot(121)
#data1.groupby('醫院等級').sum()[['醫院數','本地定點醫院數']].plot(kind="bar",width = .8) #.unstack()
#data1[['醫院數','本地定點醫院數']].plot(kind="bar",width = .8)
plt.bar(x, data1['醫院數'], width=bar_width, align="center", color="c", label="全部醫院", alpha=0.5)
plt.bar(x+bar_width, data1['本地定點醫院數'], width=bar_width, align="center", color="b", label="本地定點醫院", alpha=0.5)
plt.xticks(x+bar_width/2, tick_label)
plt.legend()
plt.title('舟山市居民就醫醫院的等級分布')
#plt.title('醫院數分布')
plt.subplot(122)
plt.bar(x, data1['總單號數'], width=bar_width, align="center", color="c", label="全部醫院", alpha=0.5)
plt.bar(x+bar_width, data1['本地定點醫院單號量'], width=bar_width, align="center", color="b", label="本地定點醫院", alpha=0.5)
plt.xticks(x+bar_width/2, tick_label)
plt.legend()
plt.title('舟山市居民在各等級醫院就醫的單號量分布')
plt.show()

堆積圖
total = df.sum(axis=1)
for i in df.columns:
df[i] = df[i] / total
bottom = 0
for i in range(df.shape[1]):
y = df.iloc[:n,i]
plt.bar(x, y, bottom=bottom)
bottom += y
plt.legend(['一級醫院','二級醫院','三級醫院'])
plt.title('100種常見病在不同醫院等級下的單號量分布圖')

柱狀折線圖 / 雙軸圖(增速要乘100的哦)
df = pd.DataFrame({'x':list('abcd'), 'y':[20, 15, 10, 8], 'r':[0.3, 0.5, 0.4, 0.1]})
#plt.rcParams['figure.figsize'] = (12.0,5.0)
fig = plt.figure(figsize=(8,4))
#畫柱子
ax1 = fig.add_subplot(111)
ax1.bar(df['x'], df['y'], alpha=.7, color='g')
ax1.set_ylabel('xx收入', fontsize=12)
plt.xticks(range(df.shape[0]), df['x'])
plt.xticks(fontsize=10) #后面設置不了
plt.yticks(fontsize=10)
#畫折線圖
ax2 = ax1.twinx()
ax2.plot(df['x'], df['r'], 'r', marker='*', ms=10)
ax2.set_ylim([0,0.6])
ax2.set_ylabel('同比增速(%)', fontsize=12)
plt.yticks(fontsize=10)
#ax1.set_xticklabels('defg', rotation=-45) #旋轉效果
plt.title('近年xx公司xx收入與同比增速', fontsize=16)
plt.grid(False)
#添加數據標簽
for i in range(df.shape[0]):
#plt.text(i, df['y'][i]+0.3, str(df['y'][i]), ha='center', va='bottom', fontsize=15, rotation=0)
plt.text(i, df['r'][i], str(df['r'][i]), ha='center', va='bottom', fontsize=12, rotation=0)
#保存與展示
#dpi為圖像分辨率, bbox_inches='tight'代表去除空白
#plt.savefig('e:/tj/month/fx1806/公司保費增速與同比.png', dpi=600, bbox_inches='tight')
plt.show()

柱狀折線圖 -- 合並label
fig = plt.figure(figsize=(10, 4)) ax1 = fig.add_subplot(111) lns1 = ax1.bar(range(ind.sum()), data.loc[ind,'單號數'], alpha=.7, color='b', label=r'單號數') ax2 = ax1.twinx() lns2 = ax2.plot(range(ind.sum()), data.loc[ind,'用葯(包含檢查等)種類數'], color='r', marker='*', ms=4, linewidth=1, label=r'用葯(包含檢查等)種類數') lns = [lns1]+lns2 labs = [l.get_label() for l in lns] ax1.legend(lns, labs, loc=0) plt.show()

其他條形圖
plt.figure(figsize=(10, 3))
#重疊條形圖
plt.subplot(121)
data_hour2015 = pd.DataFrame(np.random.randint(10, size=(100,)), columns=['num'])
data_hour2016 = pd.DataFrame(np.random.randint(10, size=(100,)), columns=['num'])
data_hour2017 = pd.DataFrame(-np.random.randint(10, size=(100,)), columns=['num'])
data_hour2015['num'].plot.bar(color='g', alpha=0.6, label='2015年')
data_hour2016['num'].plot.bar(color='r', alpha=0.6, label='2016年')
data_hour2017['num'].plot.bar(color='b', alpha=0.6, label='2017年')
#plt.ylabel('counts')
#plt.title('missing')
plt.legend(loc='upper right')
plt.xticks([0,19,39,59,79,99], [1,20,40,60,80,100])
#二維頻數分布圖
plt.subplot(122)
x = np.random.randn(1000)+2
y = np.random.randn(1000)+3
plt.hist2d(x,y,bins=40)
plt.show()

自定義圖例 參考
注意:數據點過多會導致部分bar顯示不全的情況
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
colors = ['red', 'green', 'blue']
labels = ['一級醫院', '二級醫院', '三級醫院']
c_map = data['hirate'].map(lambda x:colors[int(x)-1]).tolist()
plt.figure(figsize=(8,4))
plt.bar(range(len(data['hicode'])), data['counts'], color=c_map) #width=0.5
#plt.ylim(-0.01, 5000000)
# 自定義刻度
plt.xticks(ticks=np.arange(7)*100, labels=data['hicode'][np.arange(7)*100])
# 自定義圖例
patches = [mpatches.Patch(color=colors[i], label="{:s}".format(labels[i])) for i in range(len(colors)) ]
ax = plt.gca()
#box = ax.get_position()
#ax.set_position([box.x0, box.y0, box.width , box.height* 0.8])
ax.legend(handles=patches, loc=0) #bbox_to_anchor=(0.95,1.12)設定位置, ncol=1列數
plt.title('醫院編碼 - 接診單號量分布圖')
plt.show()

並列條形圖 -- 參考鏈接
df.groupby(['Region','Tier'],sort=True).sum()[['Sales2015','Sales2016']].unstack().plot(kind="bar",width = .8)

DataFrame數據繪圖
#柱狀圖
speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ['snail', 'pig', 'elephant','rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed, 'lifespan': lifespan}, index=index)
ax = df.plot.barh(x='lifespan')
#df.plot.bar()
#直方圖
df = pd.DataFrame(np.random.randint(1, 7, 6000), columns = ['one'])
df['two'] = df['one'] + np.random.randint(1, 7, 6000)
ax = df.plot.hist(bins=12, alpha=0.5)
#箱線圖
data = np.random.randn(25, 4)
df = pd.DataFrame(data, columns=list('ABCD'))
ax = df.plot.box()
#六邊形熱力圖
n = 10000
df = pd.DataFrame({'x': np.random.randn(n), 'y': np.random.randn(n)})
ax = df.plot.hexbin(x='x', y='y', gridsize=20)
n = 500
df = pd.DataFrame({'coord_x': np.random.uniform(-3, 3, size=n),
'coord_y': np.random.uniform(30, 50, size=n),
'observations': np.random.randint(1,5, size=n)})
ax = df.plot.hexbin(x='coord_x',
y='coord_y',
C='observations',
reduce_C_function=np.sum,
gridsize=10,
cmap="viridis")
#核密度
df = pd.DataFrame({'x': [1, 2, 2.5, 3, 3.5, 4, 5],
'y': [4, 4, 4.5, 5, 5.5, 6, 6],})
ax = df.plot.kde()
ax = df.plot.kde(bw_method=0.3)
ax = df.plot.kde(bw_method=3)
ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6])
#線圖
df = pd.DataFrame({'pig': [20, 18, 489, 675, 1776],
'horse': [4, 25, 281, 600, 1900]},
index=[1990, 1997, 2003, 2009, 2014])
lines = df.plot.line()
axes = df.plot.line(subplots=True)
lines = df.plot.line(x='pig', y='horse')
#餅圖
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
ax = df.plot.pie(y='mass', subplots=True, figsize=(6, 3))
ax = df.plot.pie(y='radius', subplots=True, figsize=(6, 3))
#散點圖
df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
[6.4, 3.2, 1], [5.9, 3.0, 2]],
columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
y='width',
c='DarkBlue')
ax2 = df.plot.scatter(x='length',
y='width',
c='species',
colormap='viridis')
矩陣圖
import pandas as pd
x = pd.DataFrame(np.random.randn(200,4)*100, columns = ['A','B','C','D'])
cs = np.random.randint(3, size=200)
#c='k',cmap=mglearn.cm3
pd.scatter_matrix(x, figsize=(8,8), c = cs, marker = '+',
diagonal='hist', hist_kwds={'bins':10, 'edgecolor':'k'},
alpha = 0.8, range_padding=0.1)
plt.show()

熱力圖
#corr = df.corr()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
fig, ax = plt.subplots(figsize = (6, 4.5))
sns.heatmap(flights, annot=True,fmt="d",linewidths=.5, ax = ax) #cmap='RdBu'
plt.show()

violinplot圖
from sklearn.datasets import load_iris iris = load_iris() df = pd.DataFrame(iris['data'], columns=iris['feature_names']) df['target'] = iris['target']
plt.figure(figsize=(9, 8)) for column_index, column in enumerate(df.columns): if column == 'target': continue plt.subplot(2, 2, column_index + 1) sns.violinplot(x='target', y=column, data=df)

數學教科書上展示的圖
plt.figure(1)
x = np.linspace(-np.pi,np.pi,256,endpoint=True)
co, si = np.cos(x), np.sin(x)
plt.plot(x, co, color="blue", linewidth=1.0, linestyle="-", label="cos", alpha=0.5)
plt.plot(x, si, "r*", markersize=1, label="sin")
#創建一個坐標軸的編輯器
ax=plt.gca()
#隱藏右邊和上邊的軸線,將左邊和下邊的軸線移到中間(數據域),把刻度數據放到下邊和左邊
ax.spines['right'].set_color("none")
ax.spines['top'].set_color("none")
ax.spines['left'].set_position(("data",0))
ax.spines['bottom'].set_position(("data",0))
ax.xaxis.set_ticks_position("bottom")
ax.yaxis.set_ticks_position("left")
#設置刻度及刻度標簽格式
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi], [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])
plt.yticks(np.linspace(-1,1,5, endpoint=True))
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(10) #字體
label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2))
#色彩填充
plt.fill_between(x, np.abs(x)<0.5, co, co>0.5, color="red", alpha=0.2)
#添加注釋
'''
xy為標注值,xycoords="data"表示使用原始坐標
xytext:文本位置,textcoords設置其坐標規范(坐標偏移)
arrowprops設置箭頭屬性(參數類型為字典), arrowstyle為箭頭風格, connectionstyle為連接風格
'''
t = 1
plt.plot([t,t], [0,np.cos(t)], 'y', color ='yellow', linewidth=2, linestyle="--")
plt.scatter([t,t], [0,np.cos(t)], 50, color ='red')
plt.annotate("cos(1)", xy=(t, np.cos(t)), xycoords="data",
xytext=(+10, +20), textcoords="offset points", fontsize=12,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
t = 2*np.pi/3
plt.plot([t,t], [0,np.sin(t)], 'y', color ='yellow', linewidth=2, linestyle="--")
plt.scatter([t,t],[0,np.sin(t)], 50, color ='green')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t,np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=12,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.title("cos&sin")
plt.legend(loc="upper left")
plt.grid(ls='--')
plt.axis([-3.15,3.15,-1.05,1.05])
plt.show()

插值圖
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
def func(x, y):
return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
plt.subplot(221)
plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
plt.plot(points[:,0], points[:,1], 'k.', ms=1)
plt.title('Original')
plt.subplot(222)
plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
plt.title('Nearest')
plt.subplot(223)
plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
plt.title('Linear')
plt.subplot(224)
plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
plt.title('Cubic')
plt.gcf().set_size_inches(6, 6)
plt.show()

等高線圖
import numpy as np
import matplotlib.pyplot as plt
#import matplotlib as mpl
#from matplotlib import colors
#建立步長為0.01,即每隔0.01取一個點
step = 0.01
x = np.arange(-10,10,step)
y = np.arange(-10,10,step)
#也可以用x = np.linspace(-10,10,100)表示從-10到10,分100份
#將原始數據變成網格數據形式
X,Y = np.meshgrid(x,y)
Z = X**2+Y**2
#等高線圖
plt.figure(figsize=(10,6)) #設置畫布大小
plt.subplot(231)
plt.contour(X,Y,Z) #等高線
plt.subplot(232)
contour = plt.contour(X,Y,Z, [20,40,60], colors='k') #只畫z=20和40的線,黑色
plt.clabel(contour, fontsize=10, colors=('k','r','b'), fmt='%.4f') #標注高度(字體,顏色,小數)
plt.subplot(233)
contour = plt.contour(X,Y,Z, 4, colors='k') #只畫z=20和40的線,黑色
plt.clabel(contour, fontsize=10, colors='b', fmt='%.2f') #標注高度(字體,顏色,小數)
plt.subplot(234)
plt.contourf(X,Y,Z) #填充顏色,f即filled
plt.xticks(()) #去掉刻度
plt.yticks(())
plt.subplot(235)
cset = plt.contourf(X,Y,Z,6,cmap=plt.cm.hot)
plt.colorbar(cset)
plt.subplot(236)
cset = plt.contourf(X,Y,Z,6,alpha=1,vmin=0,vmax=100, cmap='hot_r') #6種顏色, 顏色取反
plt.colorbar(cset)
contour = plt.contour(X,Y,Z,8,colors='k') #8條線
plt.clabel(contour,fontsize=10,colors='k')
plt.scatter(0,0,color='r')
plt.show()
#colorslist = ['w','gainsboro','gray','aqua']
#將顏色條命名為mylist,一共插值顏色條50個
#cmaps = colors.LinearSegmentedColormap.from_list('mylist',colorslist,N=200)
#cmap='hot' 'BuGn', plt.get_cmap('YlOrBr_r'), mpl.cm.hot

聚類結果的可視化(1)
from itertools import cycle
import matplotlib.pyplot as plt
plt.close('all')
plt.figure(figsize=(12,4))
plt.clf()
unique_labels = set(db.labels_)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool) # 設置一個樣本個數長度的全false向量
core_samples_mask[db.core_sample_indices_] = True #將核心樣本部分設置為true
# 使用黑色標注離散點
plt.subplot(121)
colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
if k == -1: # 聚類結果為-1的樣本為離散點
# 使用黑色繪制離散點
col = [0, 0, 0, 1]
class_member_mask = (db.labels_ == k) # 將所有屬於該聚類的樣本位置置為true
xy = X[class_member_mask & core_samples_mask] # 將所有屬於該類的核心樣本取出,使用大圖標繪制
plt.plot(xy[:, 0], xy[:, 2], 'o', markerfacecolor=tuple(col),markeredgecolor='k', markersize=14)
xy = X[class_member_mask & ~core_samples_mask] # 將所有屬於該類的非核心樣本取出,使用小圖標繪制
plt.plot(xy[:, 0], xy[:, 2], 'o', markerfacecolor=tuple(col),markeredgecolor='k', markersize=6)
plt.title('對醫院醫療耗材的異常值檢測最佳聚類數: %d' % n_clusters_)
plt.xlabel(r'CQ類材料使用頻率(%)')
plt.ylabel(r'單價200元以上CL類使用頻率(%)')
#plt.show()
plt.subplot(122)
colors = cycle('bgrcmybgrcmybgrcmybgrcmy')
for k, col in zip(unique_labels, colors):
class_member_mask = db.labels_ == k
if k == -1:
plt.plot(X[class_member_mask, 0], X[class_member_mask, 2], 'k' + '.')
else:
cluster_center = X[class_member_mask & core_samples_mask].mean(axis=0)
plt.plot(X[class_member_mask, 0], X[class_member_mask, 2], col + '.')
plt.plot(cluster_center[0], cluster_center[2], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=14)
for x in X[class_member_mask]:
plt.plot([cluster_center[0], x[0]], [cluster_center[2], x[2]], col)
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.xlabel(r'CQ類材料使用頻率(%)')
plt.ylabel(r'單價200元以上CL類使用頻率(%)')
plt.show()

聚類結果的可視化(2)
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
np.random.seed(42)
digits = load_digits()
data = scale(digits.data)
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target
sample_size = 300
print("n_digits: %d, \t n_samples %d, \t n_features %d"
% (n_digits, n_samples, n_features))
print(82 * '_')
print('init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette')
def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.v_measure_score(labels, estimator.labels_),
metrics.adjusted_rand_score(labels, estimator.labels_),
metrics.adjusted_mutual_info_score(labels, estimator.labels_,
average_method='arithmetic'),
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=sample_size)))
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
name="PCA-based",
data=data)
print(82 * '_')
# #############################################################################
# Visualize the results on PCA-reduced data
reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)
# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02 # point in the mesh [x_min, x_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()

決策樹可視化
1. 安裝繪圖軟件GraphViz(graphviz-2.38.zip 下載),並將解壓路徑添加到環境變量(通過我的電腦改環境變量貌似不行)
# 添加環境變量 import os os.environ["PATH"] += os.pathsep + 'D:/graphviz-2.38/release/bin/' # 安裝相關包 pip install graphviz pydotplus
2. 繪制決策樹
#import io
#import graphviz
import pydotplus
from sklearn.datasets import load_iris
from sklearn import tree
from IPython.display import Image
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
#tree.plot_tree(clf.fit(iris.data, iris.target))
#dot_data = tree.export_graphviz(clf, out_file=None) #黑白
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
#dot_data = io.StringIO()
#tree.export_graphviz(clf, out_file=dot_data)
#graph = graphviz.Source(dot_data)
#graph.render("iris") #導出為iris.pdf
#graph
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
Image(graph.create_png())
# ---------------------------------------------------
#from numpy import loadtxt
from sklearn.datasets import load_iris
from xgboost import XGBClassifier
from xgboost import plot_tree
import matplotlib.pyplot as plt
# load data
#iris = loadtxt('pima-indians-diabetes.csv', delimiter=",")
iris = load_iris()
# split data into X and y
X = iris.data
y = iris.target
# fit model no training data
model = XGBClassifier()
model.fit(X, y)
# plot single tree
fig = plt.figure(dpi=180)
ax = plt.subplot(1,1,1)
plot_tree(model, num_trees=4, ax = ax)
plt.show()

參考資料:
python matplotlib contour畫等高線圖
https://scikit-learn.org/stable/auto_examples/index.html 好多炫酷炸天的圖
詳解pandas.DataFrame.plot( )畫圖函數
Python模塊--PyEcharts 多種好看的圖, pyecharts官方文檔
python matplotlib quiver——畫箭頭、風場
python數據可視化seaborn(一)—— 整體樣式與調色板
Matplotlib Toolkits:三維繪圖工具包matplotlib.mplot3d
參考資料:
使用matplotlib的示例:調整字體-設置刻度、坐標、colormap和colorbar等
