1. 程式人生 > >Python 利用迴圈畫散點圖

Python 利用迴圈畫散點圖

 1 import pandas as pd
 2 data = pd.read_csv('D:/suning/iris.csv')
 3 data = data.iloc[:,1:]
 4 
 5 ###2維散點圖
 6 import matplotlib.pyplot as plt
 7 
 8 k=[
 9 'Sepal.Length',
10 'Sepal.Width',
11 'Petal.Length',
12 'Petal.Width',]
13 for i in k:
14     for m in k:
15         if i != m:
16             plt.figure(figsize=(10,10))
17 result =data.Species.unique() 18 plt.scatter(data.loc[data.Species == result[2], i], data.loc[data.Species == result[2],m], s = 35, marker='*', c ='g') 19 plt.scatter(data.loc[data.Species == result[1], i], data.loc[data.Species == result[1],m], s = 35, marker='
+', c ='r') 20 plt.scatter(data.loc[data.Species == result[0], i], data.loc[data.Species == result[0],m], s = 35, marker='o',c = 'y') 21 # 新增軸標籤和標題 22 plt.title( '') 23 plt.xlabel(i) 24 plt.ylabel(m) 25 # 去除圖邊框的頂部刻度和右邊刻度 26 #
lt.tick_params(top = 'off', right = 'off') 27 # 新增圖例plt.legend(loc = 'upper left') 28 plt.show() 29 30 ####三維散點圖 31 import numpy as np 32 import matplotlib.pyplot as plt 33 from mpl_toolkits.mplot3d import Axes3D 34 35 k=[ 36 'Sepal.Length', 37 'Sepal.Width', 38 'Petal.Length', 39 'Petal.Width',] 40 for i in k: 41 for m in k: 42 for z in k: 43 if i != m and m!=z and 1!=z: 44 plt.figure(figsize=(10,10)) 45 result = data.Species.unique() 46 ax = plt.subplot(111, projection='3d') # 建立一個三維的繪圖工程 47 ax.scatter(data.loc[data.Species == result[2], i], data.loc[data.Species == result[2], m], data.loc[data.Species == result[2], z], c='g',marker='*') # 繪製資料點 48 ax.scatter(data.loc[data.Species == result[1], i], data.loc[data.Species == result[1], m], data.loc[data.Species == result[1], z], c='r',marker='+') # 繪製資料點 49 ax.scatter(data.loc[data.Species == result[0], i], data.loc[data.Species == result[0], m], data.loc[data.Species == result[0], z], c='y',marker='o') # 繪製資料點 50 ax.set_zlabel(z) # 座標軸 51 ax.set_ylabel(m) 52 ax.set_xlabel(i) 53 plt.show() 54