柚子快報激活碼778899分享:數(shù)據(jù)可視化--頭歌數(shù)據(jù)挖掘?qū)嵱?xùn)
柚子快報激活碼778899分享:數(shù)據(jù)可視化--頭歌數(shù)據(jù)挖掘?qū)嵱?xùn)
第1關(guān):單個屬性觀測值分布——直方圖
#導(dǎo)入相關(guān)庫
import matplotlib
matplotlib.use("Agg")#控制繪圖不顯示
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#導(dǎo)入鳶尾花的數(shù)據(jù)集,并轉(zhuǎn)化成pandas的形式
from sklearn import datasets
iris = datasets.load_iris()
data = pd.DataFrame(iris.data,columns = iris.feature_names)
#選取鳶尾花數(shù)據(jù)里的 petal width (cm)列進行繪圖
x = np.array(data['petal width (cm)'])
########## Begin ##########
plt.hist(x,bins=15,color='pink',histtype='stepfilled',alpha=1)
plt.title('Petal Width')
plt.show()
########## End ##########
plt.title('sepal width')
plt.savefig('/data/workspace/myshixun/step1/image1/T1.png')
第2關(guān):單個屬性觀測值分布——盒狀圖
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn import datasets
import numpy as np
import pandas as pd
iris = datasets.load_iris()
data = pd.DataFrame(iris.data, columns=iris.feature_names)
# 選取出鳶尾花數(shù)據(jù)集的每列數(shù)據(jù),并轉(zhuǎn)化為一個列表list1
x = np.array(data['sepal length (cm)'])
y = np.array(data['sepal width (cm)'])
z = np.array(data['petal length (cm)'])
w = np.array(data['petal width (cm)'])
plt.boxplot(x=[x, y, z, w],
labels=['sepal length', 'sepal width', 'petal length', 'petal width'],
showmeans=True,
patch_artist=True,
boxprops={'color': 'yellow', 'facecolor': 'pink'},
flierprops={'marker': 'D', 'markerfacecolor': 'red', 'color': 'red'},
meanprops={'marker': 'D', 'markerfacecolor': 'black'},
medianprops={'linestyle': '--', 'color': 'green'})
# 顯示圖形
plt.ylabel('Value (centimeters)')
plt.savefig('/data/workspace/myshixun/step2/image1/T1.png')
第3關(guān):單個屬性觀測值分布——餅圖
法1:(標注了具體的顏色)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris()
# target是一個數(shù)組,存儲了data數(shù)據(jù)中每條記錄屬于哪一類鳶尾花,所以數(shù)組長度150。
# 數(shù)組元素的值共有3個(0,1,2),所以共有三種鳶尾花。(標記名)種類為山鳶尾,雜色鳶尾,維吉尼亞鳶尾。
targets = iris.target
print("標記名:",iris.target_names)
print("標記值:",targets)
dict = {}
for i in targets:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
print(dict)
value = list(dict.values())
def plot():
plt.figure(figsize=(5,5),dpi=80)
########## Begin ############
# label標簽:["Setosa", "Versicolour", "Virginica"]
# 標簽
labels =['Setosa','Versicolour','Virginica']
# 數(shù)據(jù)
values = [1, 1, 1]
# 顏色
#colors = ['blue', 'orange', 'green']
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']
# 突出部分及距離
explode = [0, 0, 0]
# 繪制餅圖,其中設(shè)置百分比,擺放角度,陰影效果
plt.pie(values, labels=labels, explode=explode, colors = colors,startangle=0, shadow=False,counterclock=True)
# 圖例,位置左上角
plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
# 使用pie函數(shù)繪制餅圖,其中x=value
# 設(shè)置圖例位置為左上角
########## End ############
# 標題:"Species"
plt.title('Species')
# 保存圖片
plt.savefig('/data/workspace/myshixun/step3/image2/pie.png')
plt.close()
法2: 默認顏色?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris()
# target是一個數(shù)組,存儲了data數(shù)據(jù)中每條記錄屬于哪一類鳶尾花,所以數(shù)組長度150。
# 數(shù)組元素的值共有3個(0,1,2),所以共有三種鳶尾花。(標記名)種類為山鳶尾,雜色鳶尾,維吉尼亞鳶尾。
targets = iris.target
print("標記名:",iris.target_names)
print("標記值:",targets)
dict = {}
for i in targets:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
print(dict)
value = list(dict.values())
def plot():
plt.figure(figsize=(5,5),dpi=80)
########## Begin ############
# label標簽:["Setosa", "Versicolour", "Virginica"]
# 標簽
labels =['Setosa','Versicolour','Virginica']
# 數(shù)據(jù)
values = [1, 1, 1]
# 顏色
#colors = ['blue', 'orange', 'green']
# 突出部分及距離
explode = [0, 0, 0]
# 繪制餅圖,其中設(shè)置百分比,擺放角度,陰影效果
plt.pie(values, labels=labels, explode=explode, startangle=0, shadow=False,counterclock=True)
# 圖例,位置左上角
plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
# 使用pie函數(shù)繪制餅圖,其中x=value
# 設(shè)置圖例位置為左上角
########## End ############
# 標題:"Species"
plt.title('Species')
# 保存圖片
plt.savefig('/data/workspace/myshixun/step3/image2/pie.png')
plt.close()
第4關(guān):兩個屬性之間的關(guān)系——散布圖
(author:強子@真我一個-CSDN博客)
import matplotlib
matplotlib.use('Agg')
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
import matplotlib.pyplot as plt
iris_dataset = load_iris()
# data 中共150條數(shù)據(jù),采集了每個樣本的4個特征
# 查看數(shù)據(jù)集的特征名稱,sepal花萼的長寬,petal花瓣的長寬
print("特征名:\n", iris_dataset['feature_names'])
# 查看前5條數(shù)據(jù)
print("前五條數(shù)據(jù):\n{}".format(iris_dataset['data'][:5]))
# 數(shù)據(jù)集拆分
iris_dataset = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'],
iris_dataset['target'],
random_state=2)
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
def plot():
######### Begin ##########
# 繪制散點矩陣圖
pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins': 20}, s=60, alpha=0.8)
######### End ##########
# 保存圖片
plt.savefig('/data/workspace/myshixun/step4/image2/scatter_matrix.png')
plt.close()
第5關(guān):時間空間數(shù)據(jù)的可視化——等高線圖 ?
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
nc_obj = Dataset('step5/ERsst.mnmean.nc')
########## Begin ##########
# 獲取 1970 年的全球海溫數(shù)據(jù)
temperature = nc_obj
temperature = temperature.variables['sst'][1970,:,:]
########## End ##########
lat, lon = temperature.shape
# 生成網(wǎng)格點坐標矩陣
X, Y = np.meshgrid(range(lon), range(lat))
# 添加畫布,畫布尺寸寬為 10,長為 5
plt.figure(figsize=(10, 5))
########## Begin ##########
# 傳入海溫數(shù)據(jù)繪制熱力圖,cmap 參數(shù)選擇 coolwarm
plt.imshow(temperature, cmap='coolwarm')
########## End ##########
# 繪制色彩子圖
x = plt.colorbar()
########## Begin ##########
# 設(shè)置子圖標簽,為 Temperature
x.set_label('Temperature')
########## End ##########
########## Begin ##########
# 畫出 7 條線,并將顏色設(shè)置為紅色
contour = plt.contour(X, Y, temperature,7, colors='r')
########## End ##########
# 等高線上標明z(即高度)的值,字體大小是7,顏色分別是紅色
plt.clabel(contour, fontsize=7, colors='r')
# 保存圖像
plt.savefig('step5/image1/test.png')
第6關(guān):時間空間數(shù)據(jù)的可視化——曲面圖
?
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 繪制3D圖形
message = np.load('step6/message.npy')
########## Begin ##########
# 根據(jù)數(shù)據(jù)簡介獲取相應(yīng)數(shù)據(jù)
x = message[:80,:]
y = message[80:160,:]
z = message[160:,:]
########## End ##########
########## Begin ##########
# 統(tǒng)一設(shè)置圖中字體大小為 20
plt.rcParams.update({'font.size':20})
# 設(shè)置圖像大小為 (10,8)和分辨為 50
fig = plt.figure(figsize=(10,8), dpi=50)
########## End ##########
ax3d = Axes3D(fig) # 將圖像轉(zhuǎn)換為 3D 模式
########## Begin ##########
# 構(gòu)建坐標系,傳入數(shù)據(jù),繪制曲面圖,顏色選用 rainbow
ax3d.plot_surface(x,y,z,cmap='rainbow')
########## End ##########
plt.xlabel('x', labelpad=10) # X軸名稱
plt.ylabel('y', labelpad=10) # Y軸名稱
ax3d.set_zlabel('z', labelpad=10) # Z軸名稱
########## Begin ##########
# 保存圖片,路徑為:step6/image1/surface_diagram.png
plt.savefig("step6/image1/surface_diagram.png")
########## End ##########
第7關(guān):時間空間數(shù)據(jù)的可視化——GIS可視化
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
names = []
pops = []
lats = []
lons = []
countries = []
with open('step7/major_city') as f:
text = f.read().split('\n')
for line in text:
info = line.split()
names.append(info[0])
pops.append(float(info[1]))
lat = float(info[2][:-1])
if info[2][-1] == 'S': lat = -lat
lats.append(lat)
lon = float(info[3][:-1])
if info[3][-1] == 'W': lon = -lon + 360.0
lons.append(lon)
country = info[4]
countries.append(country)
# ============================================
########## Begin ##########
# 設(shè)置投影模式,初始經(jīng)緯度, 緯度為 10,經(jīng)度為 100
map = Basemap(projection='ortho', lat_0=10, lon_0=100)
########## End ##########
# 畫海岸線,國家邊界,設(shè)置邊界線條的粗細
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
########## Begin ##########
# 海洋湖泊顏色為 #0099CC,陸地顏色為 #663300,經(jīng)緯線間隔 10 度
# 繪制地圖投影區(qū)域的邊緣(海洋的顏色)
map.drawmapboundary(fill_color='#0099CC')
# 畫出經(jīng)緯線
map.drawmeridians(np.arange(0,360,10))
map.drawparallels(np.arange(-90,90,10))
# 繪制顏色,zorder 為設(shè)置層級,本次是置于最低層
map.fillcontinents(color='#663300', lake_color='#0099CC', zorder=0)
########## End ##########
# 計算出地圖投影坐標的緯度/經(jīng)線網(wǎng)格
x, y = map(lons, lats)
max_pop = max(pops)
# 尺寸比例
size_factor = 80.0
# 字體顯示角度
rotation = 30
for i, j, k, name in zip(x, y, pops, names):
# 按比例計算人口顯示的散點大小
size = size_factor * k / max_pop
########## Begin ##########
# 根據(jù)人口繪制地區(qū)散點圖,顏色設(shè)置為 #FF5600
cs = map.scatter(i, j, s=size,marker='o',color='#FF5600')
########## End ##########
plt.text(i, j, name, rotation=rotation, fontsize=10)
plt.title('Some cities in the eastern hemisphere & Population')
plt.savefig('step7/image1/test.png')
第8關(guān):可視化高維度數(shù)據(jù)——數(shù)據(jù)矩陣
(author: sunny@?sdfghshvxbs的博客_CSDN博客)
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 加載數(shù)據(jù)集
iris = pd.read_csv('step8/iris.csv')
# 查看iris數(shù)據(jù)集的描述性統(tǒng)計信息
########## Begin ##########
iris.describe()
print(iris.describe())
########## End ##########
# 創(chuàng)建畫布
plt.figure(figsize=(7, 5))
# 刪除species
species = iris.pop("species")
########## Begin ##########
# 將列數(shù)據(jù)進行標準化
# 使用clustermap方法對標準化的數(shù)據(jù)繪制數(shù)據(jù)矩陣圖,standard_scale參數(shù)為1
sns.clustermap(iris,standard_scale=1)
########## End ##########
# 保存數(shù)據(jù)矩陣圖
plt.savefig('step8/stu_img/dss.png')
第9關(guān):可視化高維度數(shù)據(jù)——相關(guān)矩陣
(author: sunny@?sdfghshvxbs的博客_CSDN博客)
# -*- coding: utf-8 -*-
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
def GatherClassRanges(data, classranges):
? ? """數(shù)據(jù)預(yù)處理"""
? ? classes = data.iloc[:, 4].values
? ? length = data.iloc[:, 4].size
? ? classranges.append(0)
? ? flowertype = classes[0]
? ? for count in range(length):
? ? ? ? if flowertype != classes[count]:
? ? ? ? ? ? classranges.append(count)
? ? ? ? ? ? flowertype = classes[count]
? ? classranges.append(length)
? ? return
def GenerateDataMatrix(data, p):
? ? """創(chuàng)建矩陣"""
? ? # 將行分隔成不同的類
? ? global title
? ? classes = data.iloc[:, 4].values
? ? classranges = []
? ? GatherClassRanges(data, classranges)
? ? # 獲取不包括類名的屬性名
? ? headers = list(data)
? ? headers.pop()
? ? # 獲取列數(shù)
? ? numcol = len(data)
? ? # 每一種花
? ? # 生成一個矩陣初始化為零
? ? matrix = pd.DataFrame(np.zeros((numcol, numcol)))
? ? # 矩陣填充
? ? for i in range(numcol):
? ? ? ? for j in range(numcol):
? ? ? ? ? ? x = data.iloc[i, 0:3].values
? ? ? ? ? ? y = data.iloc[j, 0:3].values
? ? ? ? ? ? # 矩陣填充相關(guān)性值,這里閔可夫斯基距離的p設(shè)定為2
? ? ? ? ? ? matrix[i][j] = minkowskiDist(x, y, p)
? ? ? ? ? ? title = 'IrisDataset correlation Matrix'
? ? # 繪制
? ? PlotDistMatrix(matrix, title)
? ? return matrix
def PlotDistMatrix(matrix, ?title):
? ? """繪制相關(guān)性矩陣"""
? ? with sns.axes_style("white"):
? ? ? ? plt.figure()
? ? ? ? # 繪制相關(guān)性矩陣,cmap為YlGnBu
? ? ? ? ########## Begin ##########
? ? ? ? plot = sns.heatmap(matrix,cmap='YlGnBu')
? ? ? ? ########## end ##########
? ? ? ? plot.set_title(title)
? ? ? ? plt.savefig('step9/stu_img/correlation.png')
? ? ? ? return
def minkowskiDist(x, y, p):
? ? """閔可夫斯基距離"""
? ? # 根據(jù)左側(cè)公式實現(xiàn)閔可夫斯基距離函數(shù)
? ? ########## Begin ##########
? ? distance = 0
? ? for i in range(len(x)):
? ? ? ? distance += abs(x[i] - y[i]) ** p
? ? distance = distance ** (1/p)
? ? return distance
? ? ########## Begin ##########
# 導(dǎo)入數(shù)據(jù)集
data = pd.read_csv('step9/iris.csv')
GenerateDataMatrix(data, 2)
# -*- coding: utf-8 -*-
import matplotlib as mpl
# linux終端
第10關(guān):可視化高維度數(shù)據(jù)——平行坐標系
(author: sunny@?sdfghshvxbs的博客_CSDN博客)
import matplotlib as mpl
# linux終端下沒有GUI,進行設(shè)置
mpl.use('Agg')
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import parallel_coordinates
# 導(dǎo)入鳶尾花數(shù)據(jù)集
data = pd.read_csv("step10/iris.csv")
########## Begin ##########
# 對數(shù)據(jù)進行重新定序,['sepal_width', 'sepal_length', 'petal_length', 'petal_width', 'species']
data = data[['sepal_width', 'sepal_length', 'petal_length', 'petal_width', 'species']]
########## End ##########
# 繪制子圖
fig, axes = plt.subplots()
# 分類標簽
labels = ['setosa', 'versicolor', 'virginica']
# 繪制平行坐標系,class_column為數(shù)據(jù)所屬類別,axes為Matplotlib軸對象,顏色為紅綠藍。
########## Begin ##########
parallel_coordinates(data, 'species', color=['b', 'g', 'r'], ax=axes)
########## End ##########
# 保存圖片
fig.savefig('step10/stu_img/parallel.png')
柚子快報激活碼778899分享:數(shù)據(jù)可視化--頭歌數(shù)據(jù)挖掘?qū)嵱?xùn)
參考鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。