table of Contents
1 Introduction
Matplotlib Python library is a drawing provided by the library, we can easily draw the line charts, histograms, scatter plots, pie charts and other rich, installation pip install matplotlib
can be ordered, Matplotlib often with NumPy used together .
During data analysis, visualization work is a very important part of data visualization allows us to be more intuitive and clear understanding of the data, Matplotlib is a visual implementation.
2. Drawing
Let's learn how to use Matplotlib used to draw charts.
2.1 Line Chart
Line graph may be displayed with a continuous data change indicator.
2.1.1 Single Line
First, let's look at how to use Matplotlib draw a simple line chart, the specific implementation is as follows:
from matplotlib import pyplot as plt
x = range(1, 7)
y = [13, 15, 14, 16, 15, 17]
plt.title('折线图')
plt.xlabel('x 轴')
plt.ylabel('y 轴')
plt.plot(x, y)
plt.show()
Look at the results:
we will be garbled problem may be in the use of Chinese, can be solved by the following way:
① download simhei.ttf , into the site-packages\matplotlib\mpl-data\fonts\ttf
directory
② to site-packages\matplotlib\mpl-data
directory to find the matplotlibrc
file, and you can modify the following two
font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus : False
We can also change the style of the polyline, color, etc., by way of example to look at.
from matplotlib import pyplot as plt
x = range(1, 7)
y = [13, 15, 14, 16, 15, 17]
'''
figsize:设置图片的宽、高,单位为英寸
dpi:设置分辨率
'''
plt.figure(figsize=(8, 5), dpi=80)
plt.title('折线图')
plt.xlabel('x 轴')
plt.ylabel('y 轴')
'''
color:颜色
linewidth:线的宽度
marker:折点样式
linestyle:线的样式,主要包括:'-'、'--'、'-.'、':'
'''
plt.plot(x, y, color='red', marker='o', linewidth='1', linestyle='--')
# 保存
# plt.savefig('test.png')
plt.show()
Look at the results:
2.1.2 Multi-line
Sometimes we may be cases where multiple index contrast, is the need to draw a figure in multiple folds, such as: we have to understand John Doe with changes in body weight of age, example is shown below:
from matplotlib import pyplot as plt
x = range(15, 25)
y1 = [50, 55, 58, 65, 70, 68, 70, 72, 75, 70]
y2 = [52, 53, 60, 63, 65, 68, 75, 80, 85, 72]
plt.figure(figsize=(10, 6), dpi=80)
plt.title('体重年龄折线图')
plt.xlabel('年龄(岁)')
plt.ylabel('体重(kg)')
plt.plot(x, y1, color='red', label='张三')
plt.plot(x, y2, color='blue', label='李四')
# 添加网格,alpha 为透明度
plt.grid(alpha=0.5)
# 添加图例
plt.legend(loc='upper right')
plt.show()
Look at the results:
2.1.3 sub-graph
Matplotlib draw multiple sub-graphs can be achieved in a graph, we look through the examples.
from matplotlib import pyplot as plt
import numpy as np
a = np.arange(1, 30)
# 划分子图
fig, axs = plt.subplots(2, 2)
# 绘制子图
axs1 = axs[0, 0]
axs2 = axs[0, 1]
axs3 = axs[1, 0]
axs4 = axs[1, 1]
axs1.plot(a, a)
axs2.plot(a, np.sin(a))
axs3.plot(a, np.log(a))
axs4.plot(a, a ** 2)
plt.show()
Look at the results:
2.2 Scatter
Scatter with variable represents the general trend because the independent variable changes, we see examples of specific look at how to draw a scatter plot.
from matplotlib import pyplot as plt
import numpy as np
x = np.arange(0, 20)
# 生成随机数
y = np.random.randint(0, 20, size=20)
plt.title('散点图')
plt.xlabel('x 轴')
plt.ylabel('y 轴')
plt.plot(x, y, 'ob')
plt.show()
Look at the results:
2.3 Histogram
Histograms, also called quality profiles, primarily used to represent the distribution of data, we look at how to draw a histogram view by example.
import matplotlib.pyplot as plt
import numpy as np
# 生成随机数
d1 = np.random.randn(5000)
d2 = np.random.randn(4000)
'''
bins:直方图条目数
alpha:透明度
label:图例名
'''
plt.hist(d1, bins=50, label = 'label1', alpha=0.8)
plt.hist(d2, bins=50, label = 'label2', alpha=0.5)
plt.grid(alpha=0.3)
plt.title('直方图')
plt.xlabel('x 轴')
plt.ylabel('y 轴')
# 显示图例
plt.legend()
plt.show()
Look at the results:
2.4 bar
Bar the same width, with a height or length to indicate how much data it can exhaust or vertical position.
2.4.1 longitudinally mounted
First, let's look at how to draw vertical bar to student achievement as an example, look at the implementation.
import matplotlib.pyplot as plt
import numpy as np
arr = np.arange(4)
x = ['张三', '李四', '王五', '赵六']
y = [77, 79, 70, 70]
'''
width:长条形宽度
label:图例名
'''
rects = plt.bar(arr, y, width=0.3, label='语文')
'''
参数1:中点坐标
参数2:显示值
'''
plt.xticks([idx for idx in range(len(x))], x)
plt.title('学生成绩条形图')
plt.xlabel('姓名')
plt.ylabel('成绩')
plt.legend()
# 在条形图上加标注
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')
plt.show()
Look at the results:
2.4.2 Tap
We then look at how to draw again Horizontal bar through the example of view.
import matplotlib.pyplot as plt
import numpy as np
arr = np.arange(4)
y = ['张三', '李四', '王五', '赵六']
x = [88, 79, 70, 66]
plt.barh(range(4), x, 0.4, label='语文')
plt.yticks(range(4), y)
plt.xlabel('成绩')
plt.ylabel('姓名')
plt.title('学生成绩条形图')
plt.legend(loc='upper right')
for x, y in enumerate(x):
plt.text(y + 0.2, x - 0.1, '%s' % y)
plt.show()
Look at the results:
2.4.3 multiple
Finally, we look at a student to simultaneously display two language and mathematics achievement, how to draw a bar graph by Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
arr = np.arange(4)
x = ['张三', '李四', '王五', '赵六']
y1 = [88, 75, 77, 66]
y2 = [77, 79, 70, 70]
'''
width:长条形宽度
label:图例名
'''
rects1 = plt.bar(arr, y1, width=0.3, label='语文')
rects2 = plt.bar(arr + 0.3, y2, width=0.3, label='数学')
'''
参数1:中点坐标
参数2:显示值
参数3:间距
'''
plt.xticks([idx + 0.15 for idx in range(len(x))], x, rotation=10)
plt.title('学生成绩条形图')
plt.xlabel('姓名')
plt.ylabel('成绩')
plt.legend()
# 编辑文本
for rect in rects1:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')
for rect in rects2:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')
plt.show()
Look at the results:
2.5 Pie
The pie chart shows a data series, we look at how to draw a pie chart to see by way of example.
import matplotlib.pyplot as plt
label_list = ['第一部分', '第二部分', '第三部分']
size = [50, 30, 20]
# 各部分颜色
color = ['red', 'green', 'blue']
# 各部分突出值
explode = [0, 0.1, 0]
'''
explode:设置各部分突出
label:设置图例显示内容
labeldistance:设置图例内容距圆心位置
autopct:设置圆里面文本
shadow:设置是否有阴影
startangle:起始角度,默认从 0 开始逆时针转
pctdistance:设置圆内文本距圆心距离
l_text:圆内部文本
p_text:圆外部文本
'''
patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct="%1.1f%%", shadow=False, startangle=90, pctdistance=0.6)
# 设置横轴和纵轴大小相等,这样饼才是圆的
plt.axis('equal')
plt.legend(loc='upper left')
plt.show()
Look at the results: