Python數據分析-可視化“大佬”之Matplotlib

——如果有想關注Java開發相關的內容,可以轉Java修煉之道
詳細觀看——

Matplotlib——Python可視化包

折線圖繪製

折線圖適合二維的大數據集,還適合多個二維數據集的比較,主要是用於反映數據的發展趨勢變化情況。

## 採用失業率的數據集進行繪製

import numpy as np
from numpy import arange
import pandas as pd
import matplotlib.pyplot as plt
dataSet = pd.read_csv("unrate.csv")
# print(dataSet)
dataSet['DATE'] = pd.to_datetime(dataSet['DATE'])
print(dataSet.head(10))

## 繪製折線圖
plt.plot(dataSet['DATE'],dataSet['VALUE'])
plt.xticks(rotation=45)
## 添加x、y軸的標籤
plt.xlabel("Month")
plt.ylabel("Unemployment Rate")
## 添加圖標題
plt.title("Monthly Unemployment Trends, 1948")
plt.show()

Out:
	DATE  VALUE
0 1948-01-01    3.4
1 1948-02-01    3.8
2 1948-03-01    4.0
3 1948-04-01    3.9
4 1948-05-01    3.5
5 1948-06-01    3.6
6 1948-07-01    3.6
7 1948-08-01    3.9
8 1948-09-01    3.8
9 1948-10-01    3.7

## 在一個圖中畫出多個圖
dataSet['MONTH'] = dataSet['DATE'].dt.month
dataSet['MONTH'] = dataSet['DATE'].dt.month

fig = plt.figure(figsize=(10,6))

colors = ['red','blue','green','yellow','black']

for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = dataSet[start_index:end_index]
    label = str(1948+i*2)
    plt.plot(subset['MONTH'],subset['VALUE'],c=colors[i],label=label)
    
## 添加標註的位置,如果best,表示的是放在編譯器認爲組好的位置,center表示放在中間,等等還有其他的參數
plt.legend(loc='best')
plt.xlabel("MONTH")
plt.ylabel("Unemployment Rate")
## 添加圖標題
plt.title("Monthly Unemployment Trends, 1948")
plt.show()

多子圖的折線圖

主要用於多個特徵屬性的發展趨勢變化情況。

## 多子圖
women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']
#Setting Line Width
cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)
fig = plt.figure(figsize=(18, 3))

for sp in range(0,6):
    ax = fig.add_subplot(1,6,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[stem_cats[sp]], c=cb_dark_blue, label='Women', linewidth=3)
    ax.plot(women_degrees['Year'], 100-women_degrees[stem_cats[sp]], c=cb_orange, label='Men', linewidth=3)
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(stem_cats[sp])
    ## 去掉x、y軸的邊框的線
    ax.tick_params(bottom=False, top=False, left=False, right=False)
plt.legend(loc='upper right')
plt.show()

柱形圖的繪製

柱形圖適用場合是二維數據集(每個數據點包括兩個值x和y),但只有一個維度需要比較。主要是反映數據的差異,侷限性是隻限於中小規模的數據集

## 柱形圖的繪製
data = pd.read_csv("fandango_scores.csv")
cols = ['FILM', 'RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
norm_data = data[cols]
print(norm_data[:1])

#The Axes.bar() method has 2 required parameters, left and height. 
#We use the left parameter to specify the x coordinates of the left sides of the bar. 
#We use the height parameter to specify the height of each bar

num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
bar_heights = norm_data.loc[0, num_cols].values
bar_positions = arange(5) + 0.75
tick_positions = range(1,6)
fig, ax = plt.subplots()

ax.bar(bar_positions, bar_heights, 0.5)
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols, rotation=45)


## 添加x、y軸圖例以及標題
ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()

## 橫向柱形圖的繪製
import matplotlib.pyplot as plt
from numpy import arange
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']

bar_width = norm_data.loc[0,num_cols].values
bar_position = arange(5)+0.5
tick_position = range(1,6)
fig, ax = plt.subplots()

ax.barh(bar_positions, bar_width, 0.5)
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols, rotation=45)


## 添加x、y軸圖例以及標題
ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()

散點圖

散點圖是指在迴歸分析中,數據點在直角座標系平面上的分佈圖,散點圖表示因變量隨自變量而變化的大致趨勢,據此可以選擇合適的函數對數據點進行擬合。散點圖適用於三維數據集,但其中只有兩維需要比較。主要用於顯示所有的數據分佈情況。

## 散點圖的繪製
fig = plt.figure(figsize=(5,10))
subplot1 = fig.add_subplot(2,1,1)
subplot2 = fig.add_subplot(2,1,2)

subplot1.scatter(norm_data["Fandango_Ratingvalue"],norm_data['RT_user_norm'],c="red")
subplot1.set_xlabel('Fandango')
subplot1.set_ylabel('Rotten Tomatoes')
subplot1.set_title("Fig.1")

subplot2.scatter(norm_data["Fandango_Ratingvalue"],norm_data["Fandango_Ratingvalue"],c="green")
subplot2.set_xlabel('Rotten Tomatoes')
subplot2.set_ylabel('Fandango')
subplot2.set_title("Fig.2")
plt.show()

直方圖
## toolbar
fig = plt.figure(figsize=(5,5))
subplot1 = fig.add_subplot(2,1,1)
subplot2 = fig.add_subplot(2,1,2)

subplot1.hist(norm_data["RT_user_norm"],bins=20,range=(0,5))
subplot1.set_title('Distribution of Fandango Ratings')
subplot1.set_ylim(0, 20)

subplot2.hist(norm_data['RT_user_norm'], 20, range=(0, 5))
subplot2.set_title('Distribution of Rotten Tomatoes Ratings')
subplot2.set_ylim(0, 30)

plt.show()

盒圖
## 盒圖的繪製
fig = plt.figure(figsize=(5,5))
subplot = fig.subplots()
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue']
subplot.boxplot(norm_data[num_cols].values)
subplot.set_xticklabels(num_cols,rotation=90)
subplot.set_ylim(0,5)
plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章