1. 折线图
1.1 绘制一条折线
import pandas as pd
import matplotlib.pyplot as plt
unrate = pd.read_csv("unrate1.csv")
unrate["DATA"] = pd.to_datetime(unrate["DATA"])
# 获取2014年的数据
data_2014 = unrate[6:18]
print(len(data_2014))
# X 轴为时间,y轴为失业率
plt.plot(data_2014["DATA"],data_2014["UNEMPLOYMENTRATE"])
plt.xticks(rotation=90)
plt.xlabel("Month")
plt.ylabel("Unemployment Rate")
plt.title("Monthly Unemployment Trends 2014")
plt.show()
图形如下:
1.2绘制两条折线的方法:
import pandas as pd
import matplotlib.pyplot as plt
unrate = pd.read_csv("unrate1.csv")
unrate["DATA"] = pd.to_datetime(unrate["DATA"])
# 获取月份,并添加到unrate中
unrate["MONTH"] = unrate["DATA"].dt.month
# 设置图形的大小
plt.figure(figsize=[9,3])
# 绘制第一条折线
plt.plot(unrate[0:12]["MONTH"],unrate[0:12]["UNEMPLOYMENTRATE"],c="red")
# 绘制第二条折线
plt.plot(unrate[12:24]["MONTH"],unrate[12:24]["UNEMPLOYMENTRATE"],c="blue")
plt.show()
图形:
1.3 绘制多条曲线
import pandas as pd
import matplotlib.pyplot as plt
unrate = pd.read_csv("unrate1.csv")
unrate["DATA"] = pd.to_datetime(unrate["DATA"])
# 获取月份,并添加到unrate中
unrate["MONTH"] = unrate["DATA"].dt.month
# 设置图形的大小
plt.figure(figsize=[9,3])
colors =["red","green","blue","orange"]
for i in range(4):
start_index = i*12
end_index = (i+1)*12
subset = unrate[start_index:end_index]
label=str(2002+i)
# 设置标签的值
plt.plot(subset["MONTH"],subset["UNEMPLOYMENTRATE"],c=colors[i],label=label)
# 设置标签的位置
plt.legend(loc="best")
plt.xlabel('Month. Integer')
plt.ylabel("Unemployment Rate")
plt.title("Monthly Unemployment Trends 2002-2005")
plt.show()
1.4 绘制子图
import pandas as pd
import matplotlib.pyplot as plt
# 获取绘制区域
fig = plt.figure()
# 绘制 2*2 中的第一个图形
ax1 = fig.add_subplot(2,2,1)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
添加数据:
import numpy as np
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plt
# 获取绘制区域
fig = plt.figure(figsize=[12,12])
# 绘制 2*2 中的第一个图形
ax1 = fig.add_subplot(2,2,1)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
# 第一个图形的数据
ax1.plot(np.random.randint(1,50,15),np.arange(15))
# 设置刻度的间隔
ax1.xaxis.set_major_locator(MultipleLocator(5))
# 第3个图形的数据
ax3.plot(np.arange(10)*3,np.arange(10))
# 第4个图形的数据
ax4.plot(np.arange(-5,5,0.1),np.sin(np.arange(-5,5,0.1)))
ax4.xaxis.set_major_locator(MultipleLocator(1))
plt.show()
图形:
2. 条形图
import pandas as pd
import matplotlib.pyplot as plt
from numpy import arange
reviews = pd.read_csv("fandango_score_comparison.csv")
# 评分指标列
num_cols =["RT_user_norm","Metacritic_user_nom","IMDB_norm","Fandango_Ratingvalue","Fandango_Stars"]
norm_reviews = reviews[num_cols]
# 获取第-行的数据
bar_heights = norm_reviews.loc[0, num_cols].values
# 条形图的位置
bar_pos = arange(5)+0.75
# 这句可以省略.直接用plt.bar即可
fig,ax = plt.subplots()
# 参数1: 条形图位置;参数2:条形图高度,参数3:条形图宽度
ax.bar(bar_pos,bar_heights,0.3)
# 设置标签的位置
ax.set_xticks(range(1,6))
# 设置标签的内容
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.show()
print(help(plt.xticks))
3.散点图
import pandas as pd
import matplotlib.pyplot as plt
from numpy import arange
reviews = pd.read_csv("fandango_score_comparison.csv")
# 评分指标列
num_cols =["RT_user_norm","Metacritic_user_nom","IMDB_norm","Fandango_Ratingvalue","Fandango_Stars"]
norm_reviews = reviews[num_cols]
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()
4. 直方图
import pandas as pd
import matplotlib.pyplot as plt
from numpy import arange
reviews = pd.read_csv("fandango_score_comparison.csv")
# 评分指标列
num_cols =["RT_user_norm","Metacritic_user_nom","IMDB_norm","Fandango_Ratingvalue","Fandango_Stars"]
norm_reviews = reviews[num_cols]
fig,ax = plt.subplots()
# range(3,5)表示x轴的范围是3~5。bings表示直方图将3-5的区间分成多少分。
ax.hist(norm_reviews["Fandango_Ratingvalue"],range=(3,5),bins=15)
plt.show()
5. 盒图
盒图(boxplot)。它对于显示数据的离散的分布情况效果不错。
盒图是在1977年由美国的统计学家约翰·图基(John Tukey)发明的。它由五个数值点组成:最小值(min),下四分位数(Q1),中位数(median),上四分位数(Q3),最大值(max)。也可以往盒图里面加入平均值(mean)。如上图。下四分位数、中位数、上四分位数组成一个“带有隔间的盒子”。上四分位数到最大值之间建立一条延伸线,这个延伸线成为“胡须(whisker)”。
import pandas as pd
import matplotlib.pyplot as plt
from numpy import arange
reviews = pd.read_csv("fandango_score_comparison.csv")
num_cols =["RT_user_norm","Metacritic_user_nom","IMDB_norm","Fandango_Ratingvalue","Fandango_Stars"]
norm_reviews = reviews[num_cols]
fig,ax = plt.subplots()
ax.boxplot(norm_reviews["RT_user_norm"])
# 设置y轴的范围
ax.set_ylim(0,5)
plt.show()
一个图中可以显示多个盒图:
import pandas as pd
import matplotlib.pyplot as plt
from numpy import arange
reviews = pd.read_csv("fandango_score_comparison.csv")
num_cols =["RT_user_norm","Metacritic_user_nom","IMDB_no rm","Fandango_Ratingvalue","Fandango_Stars"]
norm_reviews = reviews[num_cols]
fig,ax = plt.subplots()
# norm_reviews所有列都显示为盒图
ax.boxplot(norm_reviews.values)
ax.set_xticklabels(num_cols,rotation=90)
ax.set_ylim(0,5)
plt.show()
6. 细节设置
import pandas as pd
import matplotlib.pyplot as plt
women_degrees =pd.read_csv("percent-bachelors-degrees-women-usa.csv");
major_cats =["Biology","Computer Science","Engineering","Math and Statistics"]
cb_dark_blue = (0/255,107/255,104/255)
cb_orange = (255/255,128/255,14/255)
fig = plt.figure(figsize=(18,3))
for sp in range(0,4):
ax = fig.add_subplot(1,4,sp+1)
ax.plot(women_degrees["Year"],women_degrees[major_cats[sp]],c=cb_dark_blue,label="Women",linewidth=3)
ax.plot(women_degrees["Year"],100-women_degrees[major_cats[sp]],c=cb_orange,label="Men",linewidth=3)
ax.set_xlim(1968,2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
# ax.text(2010,60,"woman")#在指定坐标上加注释
# 去除边框上的短线
plt.tick_params(bottom=False,top=False,left=False,right=False)
for key,spine in ax.spines.items():
spine.set_visible(False) # 去除边框
plt.legend(loc="upper right")
plt.show()