天天看點

matplotlib簡單四圖----條形圖,點陣圖,盒型圖,箱形圖

# -----------------------
# __Author : tyran
# __Date : 17-12-11
# -----------------------

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os

data_file_name = 'fandango_scores.csv'
data_file_path = os.path.join(os.getcwd(), 'Datas', data_file_name)
# 讀取資料
data = pd.read_csv(filepath_or_buffer=data_file_path)
"""
第一個圖開始,條形圖
"""
# 檢視的列
cols_ax1 = ['FILM', 'RottenTomatoes', 'RottenTomatoes_User', 'Metacritic']
# 擷取符合cols_ax1的四列資料
score_view = data[cols_ax1]
# 提取第一行資料的指定列
film_score = score_view.ix[0, cols_ax1[1:]]
# print(film_score)
# 圖表上每一列距離原點的距離
position = np.arange(3) + 0.5
# 設定畫布尺寸
fig = plt.figure(figsize=[6, 8])
# 設定排列位置
ax_bar = fig.add_subplot(2, 2, 1)
# 設定資料
bar_items = ax_bar.bar(position, film_score, 0.3, color='r')
# 給每一個柱子打上值
for item in bar_items:
    height = item.get_height()
    ax_bar.text(item.get_x() + item.get_width() / 2,
                1.05 * height, height,
                ha='center', va='bottom')

ax_bar.set_xticklabels(score_view[cols_ax1[0]], rotation=15)
ax_bar.set_xticks(position)
"""
第二個圖開始,點陣圖
"""
cols_scatter = ['RottenTomatoes', 'RottenTomatoes_User']
scatter_data = data[cols_scatter]
s_data1, s_data2 = scatter_data['RottenTomatoes'], scatter_data['RottenTomatoes_User']
ax_scatter = fig.add_subplot(2, 2, 2)
ax_scatter.scatter(s_data1, s_data2)
ax_scatter.set_xlabel(s_data1.name)
ax_scatter.set_ylabel(s_data2.name)

"""
第三個圖,柱形圖 資料源是Fandango_Ratingvalue和IMDB
"""
cols_tmp = ['Fandango_Ratingvalue', 'IMDB']
# 這裡就發現pandas很友善的地方了,可以通過value_counts,把Series按照值和值的出現次數重新組成Series
# 索引就是數值,值就是出現次數
# sort_index是讓他按照索引排序
fandango_data, imdb_data = data[cols_tmp[0]].value_counts().sort_index(), \
                           data[cols_tmp[1]].value_counts().sort_index()
# print(fandango_data.max())
# print(imdb_data.max())
ax_hist = fig.add_subplot(2, 2, 3)
ax_hist.set_xticks(range(0, 17, 1))
# ec是顔色  ls是樣式  lw是寬度  bins是把資料分組
ax_hist.hist(fandango_data, bins=10, color='g', ec='black', ls='--', label=fandango_data.name)
ax_hist.hist(imdb_data, bins=20, color='y', ec='black', ls='--', label=imdb_data.name)
# 顯示label
plt.legend(loc='best')

"""
第四個圖,盒形圖
"""
# 先拿資料
box_cols = ['RT_norm', 'RT_user_norm']
ax_box = fig.add_subplot(2, 2, 4)
print(data[box_cols].columns)
box = ax_box.boxplot(data[box_cols].values, labels=data[box_cols].columns,
                     showmeans=True, )
plt.show()
           
matplotlib簡單四圖----條形圖,點陣圖,盒型圖,箱形圖