Matplotlib库学习
2019-09-29 本文已影响0人
暖A暖
Matplotlib是一个Python 2D绘图库,可以生成各种硬拷贝格式和跨平台交互式环境的出版物质量数据。
Matplotlib可用于Python脚本,Python和IPython shell,Jupyter笔记本,Web应用程序服务器和四个图形用户界面工具包。
安装
python -m pip install -U pip
python -m pip install -U matplotlib
实例
绘制一个简单图像
import numpy
from matplotlib import pyplot
x = numpy.arange(1, 6)
y = 2 * x + 10
pyplot.title("Matplotlib")
pyplot.xlabel("x axis")
pyplot.ylabel("y axis")
pyplot.plot(x, y)
pyplot.show()
![](https://img.haomeiwen.com/i3260639/a16dcb7f806805c3.jpg)
绘制点
from matplotlib import pyplot
# 绘制散点图
pyplot.scatter(2, 6)
# 设置输出样式
pyplot.scatter(3, 5, s=200)
pyplot.show()
![](https://img.haomeiwen.com/i3260639/db261aa22e210482.jpg)
绘制一系列的点
from matplotlib import pyplot
x = [1, 5, 10, 15, 20]
y = [10, 20, 30, 40, 50]
pyplot.scatter(x, y, s=100)
pyplot.show()
![](https://img.haomeiwen.com/i3260639/c30576d3157d4785.jpg)
自定义颜色
matplotlib允许你给散点图中的各个点指定颜色。默认为蓝色点和黑色轮廓,在散点图包含的 数据点不多时效果很好。但绘制很多点时,黑色轮廓可能会粘连在一起。
from matplotlib import pyplot
x = list(range(1, 1001))
y = [x**2 for x in x]
pyplot.scatter(x, y, c='red', edgecolor='none', s=40)
# 设置每个坐标轴的取值范围
pyplot.axis([0, 1100, 0, 1100000])
pyplot.show()
![](https://img.haomeiwen.com/i3260639/4e82d93a68a4b19a.jpg)
柱形图
from matplotlib import pyplot
import numpy
pyplot.figure(3)
x_index = numpy.arange(5) # 柱的索引
x_data = ('A', 'B', 'C', 'D', 'E')
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
bar_width = 0.35 # 定义一个数字代表每个独立柱的宽度
rects1 = pyplot.bar(x_index, y1_data, width=bar_width, alpha=0.4, color='b', label='legend1') # 参数:左偏移、高度、柱宽、透明度、颜色、图例
rects2 = pyplot.bar(x_index + bar_width, y2_data, width=bar_width, alpha=0.5, color='r', label='legend2') # 参数:左偏移、高度、柱宽、透明度、颜色、图例
# 关于左偏移,不用关心每根柱的中心不中心,因为只要把刻度线设置在柱的中间就可以了
pyplot.xticks(x_index + bar_width/2, x_data) # x轴刻度线
pyplot.legend() # 显示图例
pyplot.tight_layout() # 自动控制图像外部边缘,此方法不能够很好的控制图像间的间隔
pyplot.show()
![](https://img.haomeiwen.com/i3260639/6b13ade1bdf363eb.jpg)
线条相关属性标记设置
线条风格linestyle或ls 描述
‘-‘ 实线
‘:’ 虚线
‘–’ 破折线
‘None‘、‘‘,’’ 什么都不画
‘-.’ 点划线
线条标记
标记maker 描述
‘o’ 圆圈
‘.’ 点
‘D’ 菱形
‘s’ 正方形
‘h’ 六边形1
‘*’ 星号
‘H’ 六边形2
‘d’ 小菱形
‘_’ 水平线
‘v’ 一角朝下的三角形
‘8’ 八边形
‘<’ 一角朝左的三角形
‘p’ 五边形
‘>’ 一角朝右的三角形
‘,’ 像素
‘^’ 一角朝上的三角形
‘+’ 加号
‘\ ‘ 竖线
‘None’,’’,’ ‘ 无
‘x’ X
颜色缩写
字符 颜色
‘b’ 蓝色
‘g’ 绿色
‘r’ 红色
‘y’ 黄色
‘c’ 青色
‘k’ 黑色
‘m’ 洋红色
‘w’ 白色