这一部分很简单,所以以代码的形式给出,在实际学习开发中,Matplotlib最好只把它当成一个画图的工具来用,没有必要深究其实现原理是什么。
一、折线图的绘制
import pandas as pd
unrate = pd.read_csv("unrate.csv")
print(unrate.head(5))
#pandas应该会自动把xxxx/xx/xx转化为标准时间格式xxxx-xx-xx,如果没有,用下面一行代码实现
# unrate["DATE"] = pd.to_datetime(unrate["DATE"])
原始数据: 代码执行结果:
import matplotlib.pyplot as plt
#画图
plt.plot()
#把画的图显示出来
plt.show()
first_twelve = unrate[0:12]
#第一个参数为横轴,第二个参数为纵轴
plt.plot(first_twelve["DATE"], first_twelve["VALUE"])
plt.show()
#可以看到上图的横坐标丑的一匹,怎么办呢
plt.plot(first_twelve["DATE"], first_twelve["VALUE"])
#指定x轴标签的角度
plt.xticks(rotation=45)
plt.show()
#给图像加标签
plt.plot(first_twelve["DATE"], first_twelve["VALUE"])
plt.xticks(rotation=45)
plt.xlabel("DATA")
plt.ylabel(‘Unemployment Rate‘)
plt.title(‘Monthly unemployment Trends, 1948‘)
plt.show()
二、子图操作
import matplotlib.pyplot as plt
#定义画图区域
fig = plt.figure()
#画子图
#前两个参数代表是一个2*2的画图区域,最后一个参数表示该子图的位置
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,4)
plt.show()
import numpy as np
#指定画图区域的大小
fig = plt.figure(figsize = (3,3))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
ax1.plot(np.random.randint(1,5,5), np.arange(5))
ax2.plot(np.arange(10)*3, np.arange(10))
plt.show()
import pandas as pd
unrate = pd.read_csv("unrate.csv")
unrate["DATE"] = pd.to_datetime(unrate["DATE"])
unrate[‘MONTH‘] = unrate[‘DATE‘].dt.month
fig = plt.figure(figsize=(6,3))
#在一个图里画多条折线,c指定颜色,可以直接是颜色名称,也可以是RGB值
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()
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‘)
plt.show()
三、条形图与散点图
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[:1] , ‘\n‘)
import matplotlib.pyplot as plt
from numpy import arange
num_cols = [
‘RT_user_norm‘, ‘Metacritic_user_nom‘, ‘IMDB_norm‘, ‘Fandango_Ratingvalue‘,
‘Fandango_Stars‘
]
#定义条形图的条高
# .ix 允许混合使用下标和名称进行选取。df.ix[[.1.],[.2.]],1框内必须统一,必须同时是下标或者名称,2框也一样。
# 1框是用来指定row,2框是指定column,但是在python3中ix是不赞成使用的
# bar_heights = norm_reviews.ix[0,num_cols].values
bar_heights = norm_reviews.loc[0][num_cols].values
print(norm_reviews.loc[0][num_cols], ‘\n\n‘, bar_heights, ‘\n‘)
#定义条的位置,即离原点有多远
bar_positions = arange(5) + 0.75
print(bar_positions)
ax = plt.subplot()
#画条形图,第三个参数定义条宽
ax.bar(bar_positions, bar_heights, 0.3)
plt.show()
bar_heights = norm_reviews.loc[0][num_cols].values
bar_positions = arange(5) + 1
#python range() 函数可创建一个整数列表
tick_positions = range(1, 6)
ax = plt.subplot()
ax.bar(bar_positions, bar_heights, 0.5)
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols, rotation=45)
ax.set_xlabel(‘Rating Source‘)
ax.set_ylabel(‘Average Rating‘)
ax.set_title(‘Average User Rating For Avengers: Age of Ultron (2015)‘)
#如果图片显示不全,用下面的命令
plt.tight_layout()
plt.show()
bar_widths = norm_reviews.loc[0][num_cols].values
bar_positions = arange(5) + 1
tick_positions = range(1, 6)
ax = plt.subplot()
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.tight_layout()
plt.show()
#画散点图
ax = plt.subplot()
ax.scatter(norm_reviews[‘Fandango_Ratingvalue‘], norm_reviews[‘RT_user_norm‘])
ax.set_xlabel(‘Fandango‘)
ax.set_ylabel(‘Rotten Tomatoes‘)
plt.show()
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()
四、柱形图与盒图
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‘, ‘Fandango_Stars‘
]
norm_reviews = reviews[cols]
# print(norm_reviews[:5])
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()
ax = plt.subplot()
#hist可以指定bins,即指定有多少个区间,bins缺省时默认是10个
ax.hist(norm_reviews[‘Fandango_Ratingvalue‘])
# ax.hist(norm_reviews[‘Fandango_Ratingvalue‘],bins=20)
# range指定显示在图上的总区间
# ax.hist(norm_reviews[‘Fandango_Ratingvalue‘], range=(4, 5), bins=20)
plt.show()
fig = plt.figure(figsize=(5, 20))
ax1 = fig.add_subplot(1, 4, 1)
ax2 = fig.add_subplot(1, 4, 2)
ax3 = fig.add_subplot(1, 4, 3)
ax4 = fig.add_subplot(1, 4, 4)
ax1.hist(norm_reviews[‘Fandango_Ratingvalue‘], bins=20, range=(0, 5))
ax1.set_title(‘Distribution of Fandango Ratings‘)
#指定y轴区间
ax1.set_ylim(0, 50)
ax2.hist(norm_reviews[‘RT_user_norm‘], 20, range=(0, 5))
ax2.set_title(‘Distribution of Rotten Tomatoes Ratings‘)
ax2.set_ylim(0, 50)
ax3.hist(norm_reviews[‘Metacritic_user_nom‘], 20, range=(0, 5))
ax3.set_title(‘Distribution of Metacritic Ratings‘)
ax3.set_ylim(0, 50)
ax4.hist(norm_reviews[‘IMDB_norm‘], 20, range=(0, 5))
ax4.set_title(‘Distribution of IMDB Ratings‘)
ax4.set_ylim(0, 50)
plt.show()
#画盒图
ax = plt.subplot()
ax.boxplot(norm_reviews[‘RT_user_norm‘])
ax.set_xticklabels([‘Rotten Tomatoes‘])
ax.set_ylim(0, 5)
plt.show()
num_cols = [
‘RT_user_norm‘, ‘Metacritic_user_nom‘, ‘IMDB_norm‘, ‘Fandango_Ratingvalue‘
]
fig, ax = plt.subplots()
ax.boxplot(norm_reviews[num_cols].values)
ax.set_xticklabels(num_cols, rotation=90)
ax.set_ylim(0, 5)
plt.tight_layout()
plt.show()
原文:https://www.cnblogs.com/gyhmolo/p/10463124.html