原始数据样本
DATE,VALUE
1948-01-01,3.4
1948-02-01,3.8
1948-03-01,4.0
1948-04-01,3.9
1948-05-01,3.5
1948-06-01,3.6
1948-07-01,3.6
1948-08-01,3.9
1948-09-01,3.8
1948-10-01,3.7
1948-11-01,3.8
1948-12-01,4.0
1949-01-01,4.3
1949-02-01,4.7
1949-03-01,5.0
1949-04-01,5.3
1. 画折线图
import matplotlib.pyplot as plt
import pandas as pd
unrate = pd.read_csv('UNRATE.csv')
twelve = unrate[0:12] # 获取前12条数据
plt.plot(twelve['DATE'], twelve['VALUE']) # 横坐标是时间,纵坐标是值
plt.show()
结果如下图:
可以看出来,横坐标的值已经挤压在一起了,
使用plt.xticks(rotation=45)
将横坐标进行旋转45度,
import matplotlib.pyplot as plt
import pandas as pd
unrate = pd.read_csv('UNRATE.csv')
twelve = unrate[0:12]
plt.plot(twelve['DATE'], twelve['VALUE'])
plt.xticks(rotation=45)
plt.show()
显示结果如下:
1.1 增加XY的label,以及title
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.plot(twelve['DATE'], twelve['VALUE'])
plt.xticks(rotation=45)
plt.show()
结果如下图
2子图
2.1添加子图
在写论文时,有很多指标,这些指标没有办法画在一张图中,因此需要画很多子图来表示。
- fig.add_subplot(4, 1, x):
4
和1
表示4行一列,顺序是从上到下,从左到右进行排序。
fig = plt.figure() # 首先指定默认画图的区间
ax1 = fig.add_subplot(4, 3, 1) # 添加子图ax1, 在当前区间,是第1个图
ax2 = fig.add_subplot(4, 3, 2) # 添加子图ax2,在当前区间,是第2个图
ax3 = fig.add_subplot(4, 3, 6) # 添加子图ax3,在当前区间,是第6个图
plt.show()
2.2 修改图片大小
fig = plt.figure(figsize=(5,3)) # 5表示图片的长,3表示图片的宽
ax1 = fig.add_subplot(2,1,1) # 添加子图1
ax2 = fig.add_subplot(2,1,2) # 添加子图2
ax1.plot(twelve['DATE'], twelve['VALUE']) # 给子图1添加数据
ax2.plot(twelve['DATE'], twelve['VALUE']) # 给子图2添加数据
plt.xticks(rotation=45)
plt.show()
2.3 在同一个图中,画两条折线
fig = plt.figure(figsize=(6,3))
plt.plot(unrate[0:12]['DATE'], unrate[0:12]['VALUE'], c='red', label='0-12') #添加一条红色的线
plt.plot(unrate[0:12]['DATE'], unrate[12:24]['VALUE'], c='blue', label='12-24') # 添加一条蓝色的线
plt.legend(loc='best') # 添加图例,best表示自动决定放到最合适的位置
plt.xticks(rotation=45)
plt.show()
结果如下:
3 柱状图
import numpy
reviews = pd.read_csv('fandango_scores.csv')
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue','Fandango_Stars']
#print(norm_reviews)
bar_heights = reviews.loc[0, num_cols].values # 每一个柱状的高度, loc表示定位第几行
print(bar_heights)
bar_positions = numpy.arange(5) + 0.75 # 每一个柱状的位置。就是离原点的位置
print(bar_positions)
fig,ax = plt.subplots() # 创建一个figure 和一组subplots
ax.bar(bar_positions, bar_heights, 0.3) #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 Ultro(2015)')
plt.show()
输出结果:
3.1 横向柱状图
import numpy
reviews = pd.read_csv('fandango_scores.csv')
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue','Fandango_Stars']
#print(norm_reviews)
bar_heights = reviews.loc[0, num_cols].values # 每一个柱状的高度
print(bar_heights)
bar_positions = numpy.arange(5) + 0.75 # 每一个柱状的位置。就是离原点的位置
print(bar_positions)
fig,ax = plt.subplots() # 创建一个figure 和一组subplots
ax.barh(bar_positions, bar_heights, 0.3) #0.3表示柱状条形图宽度, barh表示横向画图
ax.set_yticks(range(1, 6))
ax.set_yticklabels(num_cols, rotation=45)
ax.set_xlabel('Average Rating')
ax.set_ylabel('Rating Source')
ax.set_title('Average User Rating For Avengers: Age of Ultro(2015)')
plt.show()
输出结果:
3.2 按照x轴数据归类来画柱状图
当x轴上的数据非常多的时候,不方便将每个x轴数据进行显示,可以进行归类,如下图:
fig, ax = plt.subplots()
ax.hist(norm_reviews['Fandango_Ratingvalue'])
plt.show()
输出结果如下:
默认情况下,hist
按照10个进行统计。可以指定个数:
ax.hist(norm_reviews['Fandango_Ratingvalue'], bins=20)
这样会自动划分20个区间,那么输出结果如下:
同时,还可以指定具体某一个区间,比如只显示区间(4,5)之间的数据,ax.hist(norm_reviews['Fandango_Ratingvalue'], range=(4,5),bins=20)
如下图所示:
同时可以指定y轴和x轴的区间范围:
ax2.hist(norm_reviews['RT_user_norm'], 20, range=(0,5)) # 可以省略bins
ax2.set_title('Distribution of Rotten Tomatoes Ratings')
ax2.set_ylim(0, 50) # 指定y轴的区间
输出结果如下:
指定横轴区间
import matplotlib.pyplot as plt
height = [168,155,182,170,173,161,155,173,176,181,166,172,170]
bins = range(150, 191, 5) # 指定横轴区间
plt.hist(height, bins=bins)
plt.show()
条形图
条形图是用宽度相同的条形的高度或长短来表示数据多少的图形。
import matplotlib.pyplot as plt
classes = ['class1', 'class2', 'class3']
scores = [70,80,60]
plt.bar(classes,scores)
plt.show()
4 散点图
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()
输出结果:
5 盒图
fig, ax = plt.subplots()
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue']
ax.boxplot(norm_reviews[num_cols])
ax.set_xticklabels(num_cols, rotation=90)
ax.set_ylim(0,5)
plt.show()
输出结果如下:
6 饼图
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
labels = ['房贷', '饮食', '出行', '教育']
data = [8000, 2000, 2000, 3000]
plt.pie(data, labels=labels, autopct='%1.1f%%') # autopct表示显示百分比
中文设置
默认情况下中文设置会显示乱码,如下代码所示:
import matplotlib.pyplot as plt
x=[1,2]
y=[3,4]
plt.title('中文标题')
plt.bar(x,y)
plt.show()
结果如下:
可以看出来中文显示乱码了。
import matplotlib.pyplot as plt
import matplotlib as mpl
x=[1,2]
y=[3,4]
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.title('中文标题')
plt.bar(x,y)
plt.show()
可以添加参数rcParams
负号乱码
当我们的数值中包含负号时,默认也会出现乱码现象:
import matplotlib.pyplot as plt
import matplotlib as mpl
x=[1,2]
y=[-3,4]
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.title('中文标题')
plt.bar(x,y)
plt.show()
同样可以通过设置参数进行修改:
import matplotlib.pyplot as plt
import matplotlib as mpl
x=[1,2]
y=[-3,4]
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文支持
mpl.rcParams['axes.unicode_minus'] = False # 正常显示负号
plt.title('中文标题')
plt.bar(x,y)
plt.show()
修改线条样式
折线图:
import matplotlib.pyplot as plt
import matplotlib as mpl
x=[1,2]
y=[-3,4]
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.title('中文标题')
plt.plot(x,y)
plt.show()
设置线条类型:
import matplotlib.pyplot as plt
import matplotlib as mpl
x=[1,2]
y=[-3,4]
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文支持
mpl.rcParams['axes.unicode_minus'] = False # 正常显示负号
mpl.rcParams['lines.linewidth'] = 5 # 设置线条宽度
mpl.rcParams['lines.color'] = 'red' # 设置线条颜色
mpl.rcParams['lines.linestyle'] = '--' # 设置线条样式
plt.title('中文标题')
plt.plot(x,y)
plt.show()
设置title xlable ylabel xticks
x = [1,2,3]
name = ['A班', 'B班', 'C班']
y = [80, 85, 75]
plt.bar(x, y)
plt.title("三班成绩柱状图")
plt.xlabel('班级')
plt.ylabel('成绩')
plt.xticks(x, name) # 将1对应为A班,2对应为B班,3对应为C班
plt.text(1, 81,80) # 在(1,81)位置上添加文字80
plt.text(2, 86, 85) # 在(2,86)位置上添加文字85