1. 程式人生 > >Python視覺化庫Matplotlib的使用

Python視覺化庫Matplotlib的使用

一。匯入資料

import pandas as pd
unrate = pd.read_csv('unrate.csv')
unrate['DATE'] = pd.to_datetime(unrate['DATE'])
print(unrate.head(12))
 結果如下:
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 10 1948-11-01 3.8 11 1948-12-01 4.0
二。使用Matplotlib庫
import matplotlib.pyplot as plt
#%matplotlib inline
#Using the different pyplot functions, we can create, customize, and display a plot. For example, we can use 2 functions to :
plt.plot()
plt.show()

結果如下:

三。插入資料

first_twelve = unrate[0:12]
plt.plot(first_twelve['DATE'], first_twelve['VALUE'])
plt.show()

 由於x軸過於緊湊,所以使用旋轉x軸的方法 結果如下。

plt.plot(first_twelve['DATE'], first_twelve['VALUE'])
plt.xticks(rotation=45)
#print help(plt.xticks)
plt.show()

四。設定x軸y軸說明

plt.plot(first_twelve['DATE'], first_twelve['VALUE'])
plt.xticks(rotation=90)
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title('Monthly Unemployment Trends, 1948
') plt.show()

五。子圖設定

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(4,3,1)
ax2 = fig.add_subplot(4,3,2)
ax2 = fig.add_subplot(4,3,6)
plt.show()

 六。一個圖示多個曲線。

1.簡單實驗。

複製程式碼
unrate['MONTH'] = unrate['DATE'].dt.month
unrate['MONTH'] = unrate['DATE'].dt.month
fig = plt.figure(figsize=(6,3))

plt.plot(unrate[0:12]['MONTH'], unrate[0:12]['VALUE'], c='red')
plt.plot(unrate[12:24]['MONTH'], unrate[12:24]['VALUE'], c='blue')

plt.show()
複製程式碼

2.使用迴圈

複製程式碼
fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i])
   
plt.show()
複製程式碼

3.設定標籤

複製程式碼
fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    label = str(1948 + i)
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label)
plt.legend(loc='best')
#print help(plt.legend)
plt.show()
複製程式碼

 4。設定完整標籤

複製程式碼
fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    label = str(1948 + i)
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label)
plt.legend(loc='upper left')
plt.xlabel('Month, Integer')
plt.ylabel('Unemployment Rate, Percent')
plt.title('Monthly Unemployment Trends, 1948-1952')

plt.show()
複製程式碼

 七。折線圖(某電影評分網站)

1.讀取資料

import pandas as pd
reviews = pd.read_csv('fandango_scores.csv')
cols = ['FILM', 'RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
norm_reviews = reviews[cols]
print(norm_reviews[:10])

  2.設定說明

複製程式碼
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
bar_heights = norm_reviews.ix[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.bar繪製折線圖,bar_positions繪製離遠點的距離,0.5繪製離折線圖的寬度。
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols, rotation=45)//橫軸的說明 旋轉45度 橫軸說明

ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()
複製程式碼

3.旋轉x軸 y軸

複製程式碼
import matplotlib.pyplot as plt
from numpy import arange
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']

bar_widths = norm_reviews.ix[0, num_cols].values
bar_positions = arange(5) + 0.75
tick_positions = range(1,6)
fig, ax = plt.subplots()
ax.barh(bar_positions, bar_widths, 0.5)

ax.set_yticks(tick_positions)
ax.set_yticklabels(num_cols)
ax.set_ylabel('Rating Source')
ax.set_xlabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()
複製程式碼

八。 散點圖

1。基本散點圖

fig, ax = plt.subplots()
ax.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['RT_user_norm'])
ax.set_xlabel('Fandango')
ax.set_ylabel('Rotten Tomatoes')
plt.show()

2.拆分散點圖

複製程式碼
#Switching Axes
fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
ax1.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['RT_user_norm'])
ax1.set_xlabel('Fandango')
ax1.set_ylabel('Rotten Tomatoes')
ax2.scatter(norm_reviews['RT_user_norm'], norm_reviews['Fandango_Ratingvalue'])
ax2.set_xlabel('Rotten Tomatoes')
ax2.set_ylabel('Fandango')
plt.show()
複製程式碼

Ps:還是呈現很強的相關性的,基本呈直線分佈

九。直方圖

 1.讀入資料

import pandas as pd
import matplotlib.pyplot as plt
reviews = pd.read_csv('fandango_scores.csv')
cols = ['FILM', 'RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue']
norm_reviews = reviews[cols]
print(norm_reviews[:100])

   2.統計評分個數

複製程式碼
fandango_distribution = norm_reviews['Fandango_Ratingvalue'].value_counts()//統計
fandango_distribution = fandango_distribution.sort_index()//排序

imdb_distribution = norm_reviews['IMDB_norm'].value_counts()
imdb_distribution = imdb_distribution.sort_index()

print(fandango_distribution)
print(imdb_distribution)
複製程式碼

3.畫直方圖

fig, ax = plt.subplots()
#ax.hist(norm_reviews['Fandango_Ratingvalue'])
#ax.hist(norm_reviews['Fandango_Ratingvalue'],bins=20)
ax.hist(norm_reviews['Fandango_Ratingvalue'], range=(4, 5),bins=20)//劃分的區間20個,只統計4-5區間的bins
plt.show()

4.不同的媒體評分圖

複製程式碼
fig = plt.figure(figsize=(5,20))
ax1 = fig.add_subplot(4,1,1)
ax2 = fig.add_subplot(4,1,2)
ax3 = fig.add_subplot(4,1,3)
ax4 = fig.add_subplot(4,1,4)
ax1.hist(norm_reviews['Fandango_Ratingvalue'], bins=20, range=(0, 5))
ax1.set_title('Distribution of Fandango Ratings')
ax1.set_ylim(0, 50)

ax2.hist(norm_reviews['RT_user_norm'], 20, range=(0, 5))
ax2.set_title('
            
           

相關推薦

Python視覺Matplotlib的使用

一。匯入資料import pandas as pd unrate = pd.read_csv('unrate.csv') unrate['DATE'] = pd.to_datetime(unrate['DATE']) print(unrate.head(12)) 結果如下:

Python視覺matplotlib各種圖demo

關聯分析、數值比較:散點圖、曲線圖 分佈分析:灰度圖、密度圖 涉及分類的分析:柱狀圖、箱式圖 核密度估計(Kernel density estimation),是一種用於估計概率密度函式的非引數方法,採用平滑的峰值函式(“核”)來擬合觀察到的資料點,從而對真

Python視覺 python視覺--matplotlib

 轉自小小蒲公英原文用Python視覺化庫 現如今大資料已人盡皆知,但在這個資訊大爆炸的時代裡,空有海量資料是無實際使用價值,更不要說幫助管理者進行業務決策。那麼資料有什麼價值呢?用什麼樣的手段才能把資料的價值直觀而清晰的表達出來?答案是要提供像人眼一樣的直覺的、互動的和反應靈敏的視覺化環境。資料

Python視覺Matplotlib(4.三種設定樣式方法、設定座標刻度以及標籤、設定顯示出特殊字元)

1.三種設定方式   (1)向方法傳入關鍵字引數 上一節已經總結過,一直在使用   (2)對例項使用一系列的setter方法           具體的方法直接看程式碼  import matplotli

Python視覺Matplotlib(3.線條的詳細樣式及線性、儲存圖片、plot的詳細風格和樣式)、背景色、點和線的詳細設定

1.修改線條的樣式: linestyle、color、marker(標記) ''' 顏色 color:修改顏色,可以簡寫成c 樣式 linestyle='--' 修改線條的樣式 可以簡寫成 ls 標註 marker : 標註 線寬 linewidth: 設

Python視覺Matplotlib繪圖(2.設定範圍、標籤、標題、圖例(詳細引數))

1.為繪製的圖新增範圍 import matplotlib.pyplot as plt # 匯入繪圖模組 import numpy as np # 匯入需要生成資料的numpy模組 '''新增範圍''' y = np.arange(0,10,1) plt.plo

視覺-Matplotlib-盒圖(第四天)

盒圖由五個數值點組成,最小觀測值,下四分位數,中位數,上四分位數,最大觀測值 IQR = Q3 - Q1  Q3表示上四分位數, Q1表示下四分位數,IQR表示盒圖的長度 最小觀測值 min =Q1 - 1.5*IQR 最大觀測值 max=Q3 + 1.5*IQR  , 大於最大值或

視覺-Matplotlib-直方圖(第四天)

1.plt.hist(array, bins, color)  # array表示數值, bins表示的是bin的範圍 data = np.random.normal(0, 20, 1000) # 畫出bins值 bins = np.arange(-100, 100, 5) plt.hist

視覺-Matplotlib-散點圖(第四天)

1. 畫基本的散點圖 plt.scatterdata[:, 0], data[:, 1], marker='o', color='r', label='class1', alpha=0.4) np.random.multivariate_normal 根據均值和協方差生成多行列表 mu_vec1 =

視覺-Matplotlib-3D圖(第四天)

1. 畫三維圖片圖 axes = Axes3D(fig)這一步將二維座標轉換為三維座標,axes.plot_surface() import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axe

python視覺Matplotlib 繪製】視覺圖片中顯示中文

# ----------------------顯示中文----神奇般的存在---------------- from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei'] # ----------------------

高效使用 Python 視覺工具 Matplotlib

Matplotlib是Python中最常用的視覺化工具之一,可以非常方便地建立海量型別的2D圖表和一些基本的3D圖表。本文主要介紹了在學習Matplotlib時面臨的一些挑戰,為什麼要使用Matplotlib,並推薦了一個學習使用Matplotlib的步驟。 簡介 對於新手來說

視覺----Matplotlib+Pandas高階篇及應用

以下文件的原始檔,我做成網頁了,可以直接點選這裡 一、柱狀圖詳解 import matplotlib.pyplot as plt import numpy as np plt.rcParams["font.sans-serif"]=['Si

Python數據可視-Matplotlib

img use class 一個 pri style randint degree spl 折線圖繪制: import pandas as pd unrate = pd.read_csv(‘unrate.csv‘) unrate[‘DATE‘] = pd.to_date

python視覺互動dash

R有shiny,應該是非常好用的,python像shiny的互動視覺化的庫不多,dash其中之一,簡單實用,但整體似乎還不如shiny。 1安裝 pip install dash pip install dash-renderer pip install dash-html-

Python視覺中的Matplotlib(6.散點圖以及詳細引數、為圖形新增文字、註釋、箭頭以及它們的引數)

1. 散點圖        散點圖需要兩個引數x,y , 但此時,x不是表示x軸的刻度,而是每個點的橫軸座標!    散點圖 scatter() 引數說明:         &n

Python視覺中的Matplotlib(5.直方圖、條形圖以及餅圖的用法和詳細的引數)

1.  直方圖   hist()      直方圖的引數只有一個X import matplotlib.pyplot as plt # 匯入繪圖模組 import numpy as np # 匯入需要生成資料的numpy模組 '

Python視覺中的Matplotlib繪圖(1.畫圖,網格,子圖,畫正餘弦圖,座標軸界限,畫圓,)

1.一張基本的圖示包含的元素;    · x軸和y軸 以及他們的刻度線 、標籤、繪圖區域 import matplotlib.pyplot as plt # 匯入繪圖模組 import numpy as np # 匯入需要生成資料的num

智聯Python相關職位的資料分析及視覺-Pandas&Matplotlibpython

Numpy(Numerical Python的簡稱)是Python科學計算的基礎包。它提供了以下功能: 快速高效的多維陣列物件ndarray。 用於對陣列執行元素級計算以及直接對陣列執行數學運算的函式。 用於讀寫硬碟上基於陣列的資料集的工具。 線性代數運算、傅立

Python資料視覺matplotlib實踐chapter-01

""" Example 1.3.1: 函式plot() """ import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.05,10,1000) # x = 0.05到10的等間距1000個點 y = np