python工具包--Matplotlib

简介: python工具包--Matplotlib

同样的,Matplotlib官方的参考文档: https://matplotlib.org/api/index.html

里面有很多的绘制好的图表,我们如果需要非常细节的图形,可以找一个类似的模板然后传入我们需要的数据就可以了


官方提供的模板链接如下:https://matplotlib.org/gallery/index.html


我下面做一个简单的使用记录


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline


Matplotlib的基本操作


# 最基本的一个图
plt.plot([1,2,3,4,5],[1,4,9,16,25])
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel')


Text(0, 0.5, 'ylabel')

image.png


以下是 常见的线条类型 使用

image.png


颜色

表示颜色的字符参数有:

image.png


# 指定不同的参数来绘图:下面简单介绍几种,了解即可
# 'bs'可以设置线条的形状和颜色(也可以通过color与linestyle分开设置)
# fontsize可以设置坐标轴字体的大小
# marker可以设置标志点的形状
# markerfacecolor可以设置标志的颜色
# markersize可以设置标志的大小
# alpha可以设置透明度
x = np.linspace(-10,10)
y = np.sin(x)
plt.plot(x,y,color='b',linestyle='-',marker = '*',markerfacecolor='y',markersize = 5,alpha = 0.4)
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel',fontsize = 16)


Text(0, 0.5, 'ylabel')

image.png

# 211 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第1个图
plt.subplot(211)
plt.plot(x,y,color='r')
# 212 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第2个图
plt.subplot(212)
plt.plot(x,y,color='b')


[<matplotlib.lines.Line2D at 0x19251924b48>]

image.png


# 211 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第1个图
plt.subplot(121)
plt.plot(x,y,color='k')
# 212 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第2个图
plt.subplot(122)
plt.plot(x,y,color='y')


[<matplotlib.lines.Line2D at 0x19252dc1a08>]

image.png


# 可以创建多行多列,如果当前的子图没有执行绘图操作,则该位置的子图会空出来
plt.subplot(221)
plt.plot(x,y,color='r')
plt.subplot(224)
plt.plot(x,y,color='b')


[<matplotlib.lines.Line2D at 0x19252f37e88>]

image.png


# 关于参数的用法和选择,详细的可以查看官方文档
# 添加解释和标注
plt.plot(x,y,color='k',linestyle='-',linewidth = 3,marker = 'o',markerfacecolor='r',markersize = 5)
plt.xlabel('x:---')
plt.ylabel('y:---')
# 图题
plt.title('title:Clichong')
# 在指定的位置添加注释
plt.text(0,0,'pos(0,0)')
#显示网络
plt.grid(True)
# 添加箭头,需给定其实和终止位置以及箭头的各种属性
plt.annotate('pos(-5,0)',xy=(-4,0),xytext=(-2.8,0.3),arrowprops = dict(facecolor='blue',shrink=0.15,headlength= 20,headwidth = 3))
# 将坐标轴隐藏
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

image.png


import math
x = np.random.normal(loc = 0.0,scale=1.0,size=300)
width = 0.5
bins = np.arange(math.floor(x.min())-width,math.ceil(x.max())+width,width)
ax = plt.subplot(111)
# 去掉上方和右方的坐标轴线
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# 隐藏坐标轴上的锯齿线
plt.tick_params(bottom='off',top='off',left = 'off',right='off')
# 加入网络
plt.grid()
# 绘制直方图
plt.hist(x,alpha = 0.5,bins = bins)


(array([ 0.,  3.,  5., 14., 26., 53., 50., 54., 41., 31., 15.,  7.,  1.]),
 array([-3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,
         2. ,  2.5,  3. ]),
 <a list of 13 Patch objects>)

image.png


# legend函数实现给出颜色与类别的对应图,loc='best'是自动找到一个合适的位置,通过help(plt.legand)可以找到其他的参数
fig = plt.figure()
ax = plt.subplot(111)
x = np.arange(10)
for i in range(1,4):
    plt.plot(x,i*x**2,label = 'Group %d'%i)
ax.legend(loc='upper center',bbox_to_anchor = (0.5,1.15) ,ncol=3)
<matplotlib.legend.Legend at 0x1925832da48>

image.png


风格设置


# 以下为可以调用的风格
plt.style.available


['bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark-palette',
 'seaborn-dark',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'seaborn',
 'Solarize_Light2',
 'tableau-colorblind10',
 '_classic_test']


# 尝试风格dark_background
x = np.linspace(-10,10)
y = np.sin(x)
plt.style.use('dark_background')
plt.plot(x,y)


[<matplotlib.lines.Line2D at 0x19258ad46c8>]

image.png


x = np.linspace(-10,10)
y = np.sin(x)
plt.xkcd()
plt.plot(x,y)
fig = plt.gca()

image.png


条形图


# 取消上诉的扭曲风格
# plt.xkcd(False)
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5,5,5)
fig,axes = plt.subplots(ncols = 2)
# bar绘制正常的条形图
v_bars = axes[0].bar(x,y,color='red')
# barh绘制横着的条形图
h_bars = axes[1].barh(x,y,color='red')
# 通过子图索引设置各自的细节
axes[0].axhline(0,color='grey',linewidth=2)
axes[1].axvline(0,color='grey',linewidth=2)
plt.show()

image.png

# 数值
mean_values = [1,2,3]
# 误差棒
variance = [0.2,0.4,0.5]
# 名字
bar_label = ['bar1','bar2','bar3']
# 指定位置
x_pos = list(range(len(bar_label)))    # [0, 1, 2, 3]
# 带有误差棒的条形图
plt.bar(x_pos,mean_values,yerr=variance,alpha=0.3)
# 可以自己设置坐标轴的取值范围
max_y = max(zip(mean_values,variance)) #(3, 0.5)
plt.ylim([0,(max_y[0]+max_y[1])*1.2])
# y轴标签
plt.ylabel('variable y')
# x轴标签
plt.xticks(x_pos,bar_label)
plt.show()

image.png


# 图像对应着绘图的结果
patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
mean_value = range(1,len(patterns)+1)
# 确定每一个线条的位置
x_pos = list(range(len(mean_value)))
# 竖着画
bars = plt.bar(x_pos,mean_value,color='white')
# 通过参数设置条的样式
for bar,pattern in zip(bars,patterns):
    bar.set_hatch(pattern)
plt.show()

image.png

data = range(200, 225, 5)
bar_labels = ['a', 'b', 'c', 'd', 'e']
y_pos = np.arange(len(data))     # array([0, 1, 2, 3, 4])
fig = plt.figure(figsize=(10,8))
# 设置y轴标签,用bar_labels带替y_pos
plt.yticks(y_pos, bar_labels, fontsize=16)
# 横着画
bars = plt.barh(y_pos,data,alpha = 0.5,color='g')
# 设置一条最低点的竖线
plt.vlines(min(data),-1,len(data)+0.5,linestyle = 'dashed')
# 设置每个条形图的数值
for b,d in zip(bars,data):
    plt.text(b.get_width()+b.get_width()*0.05,b.get_y()+b.get_height()/2,'{0:.2%}'.format(d/min(data)))
plt.show()

image.png


盒图


盒图boxplot由最小值(min),下四分位数(q1),中位数(median),上四分位数(q3),最大值(max)五部分组成。

# 参数的介绍,详细的可查看参考文档,需要时再查阅
#print(help(plt.boxplot))


# 以下是一个简单的例子
tang_data = [np.random.normal(0,std,100) for std in range(1,4)]
fig = plt.figure(figsize = (8,6))
plt.boxplot(tang_data,notch=False,sym='s',vert=True)
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('box plot')


Text(0.5, 1.0, 'box plot')

image.png


直方图


data = np.random.normal(0,20,1000)
bins = np.arange(-100,100,5)
plt.hist(data,bins=bins)
# 由于会堆叠在一起,可以调整x坐标轴
#plt.xlim([min(data)-5,max(data)+5])
plt.show()

image.png

import random
# 两个类别来对比
data1 = [random.gauss(15,10) for i in range(500)]
data2 = [random.gauss(5,5) for i in range(500)]
# 指定区间
bins = np.arange(-50,50,2.5)
# 别分绘制,为了避免重叠需要设置透明度aplha
plt.hist(data1,bins=bins,label='class 1',alpha = 0.3)
plt.hist(data2,bins=bins,label='class 2',alpha = 0.3)
# 自动分配颜色既放置在合适位置
plt.legend(loc='best')
plt.show()

image.png


散点图


N = 1000
x = np.random.randn(N)
y = np.random.randn(N)
# 绘制散点图
plt.scatter(x,y,alpha=0.5)
#plt.legend(loc='best')
# plt.grid(True)
plt.show()

image.png


3D图


# 需要额外的导入绘制3D图的工具
from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111,projection = '3d')
#ax = fig.gca(projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): 
    xs = np.arange(20)
    ys = np.random.rand(20)
    cs = [c]*len(xs)
    ax.bar(xs,ys,zs = z,zdir='y',color = cs,alpha = 0.5)
plt.show()

image.png

fig = plt.figure()
ax = fig.add_subplot(111,projection = '3d')
#( 设置-4π~4π的取值范围,数量为100个)
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)   
#( 设置-2~2的取值范围,数量为100个)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x,y,z)
#plt.show()


[<mpl_toolkits.mplot3d.art3d.Line3D at 0x1b03fbd5608>]

image.png

fig = plt.figure()  
ax = fig.add_subplot(111, projection='3d') 
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): 
    xs = np.arange(20)       # 0-20的数组
    ys = np.random.rand(20)  # 0-1取值范围的随机小数数组
    cs = [c]*len(xs)         # 颜色取值数组
    ax.bar(xs,ys,zs = z,zdir='y',color = cs,alpha = 0.5)
plt.show()

image.png


圆饼图


m = 51212.
f = 40742.
m_perc = m/(m+f)
f_perc = f/(m+f)
colors = ['navy','lightcoral']
labels = ["Male","Female"]
plt.figure(figsize=(8,8))
paches,texts,autotexts = plt.pie([m_perc,f_perc],labels = labels,autopct = '%1.1f%%',explode=[0,0.05],colors = colors)
for text in texts+autotexts:
    text.set_fontsize(20)
for text in autotexts:
    text.set_color('white')

image.png


布局设置


# 3x3的布局,第一个子图
ax1 = plt.subplot2grid((3,3),(0,0))
# 布局大小都是3z3,各自的位置不同
ax2 = plt.subplot2grid((3,3),(1,0))
# 占用一些位置,一个顶3个
ax3 = plt.subplot2grid((3,3),(0,2),rowspan=3)
#同上,越界一个顶两个
ax4 = plt.subplot2grid((3,3),(2,0),colspan = 2)
ax5 = plt.subplot2grid((3,3),(0,1),rowspan=2)

image.png

x = np.linspace(0,10,1000)
y1 = x**2
y2 = np.sin(x**2)
fig,ax1 = plt.subplots()
# 设置嵌套图位置,其参数分别表示:
# left:绘图区左侧边缘线与Figure画布左侧边缘线的距离
# Bottom:绘图区底侧边缘线与Figure画布底侧边缘线的距离
# width:绘图区的宽度
# height:绘图区的高度
left,bottom,width,height = [0.22,0.45,0.3,0.35]
#加入嵌套图
ax2 = fig.add_axes([left,bottom,width,height])
# 分别绘制
ax1.plot(x,y1)
ax2.plot(x,y2)


[<matplotlib.lines.Line2D at 0x1b0419bba48>]

image.png


模板引用


示例1:Horizontal bar chart模板

import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(100)
plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.show()

image.png


示例2:Creating annotated heatmaps

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
              "potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
           "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
                    [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
                    [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
                    [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
                    [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
                    [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
                    [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax = plt.subplots()
im = ax.imshow(harvest)
# We want to show all ticks...
ax.set_xticks(np.arange(len(farmers)))
ax.set_yticks(np.arange(len(vegetables)))
# ... and label them with the respective list entries
ax.set_xticklabels(farmers)
ax.set_yticklabels(vegetables)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(vegetables)):
    for j in range(len(farmers)):
        text = ax.text(j, i, harvest[i, j],
                       ha="center", va="center", color="w")
ax.set_title("Harvest of local farmers (in tons/year)")
fig.tight_layout()
plt.show()

image.png

目录
相关文章
|
30天前
|
数据可视化 数据挖掘 Python
Python数据可视化:探索Matplotlib的强大功能
数据可视化在如今的数据分析和展示中扮演着至关重要的角色。本文将介绍Python中常用的数据可视化库Matplotlib,深入探讨其功能和应用,帮助读者更好地利用Matplotlib进行数据可视化。
|
29天前
|
机器学习/深度学习 数据可视化 数据处理
Python数据可视化:探索Matplotlib库的强大功能
本文将深入探讨Python中用于数据可视化的重要工具之一——Matplotlib库。通过介绍Matplotlib库的基本概念、常用功能和实际应用案例,帮助读者更好地了解如何利用Matplotlib创建各种吸引人的数据图表。
|
1月前
|
数据可视化 数据挖掘 Python
Python中的数据可视化利器Matplotlib详解
本文将深入探讨Python中一款强大的数据可视化工具——Matplotlib,介绍其基本用法、常见图表类型以及高级定制技巧,帮助读者更好地利用Matplotlib实现数据可视化需求。
|
4天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
6天前
|
Python
掌握Python导包技艺:揭秘导包语句的奥秘
掌握Python导包技艺:揭秘导包语句的奥秘
15 0
|
7天前
|
测试技术 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,用于修改函数或方法的行为。本文将深入探讨Python中装饰器的概念、用法和实际应用,以及如何利用装饰器实现代码的优雅和高效。
|
25天前
|
数据采集 搜索推荐 数据挖掘
使用Python制作一个批量查询搜索排名的SEO免费工具
最近工作中需要用上 Google SEO(搜索引擎优化),有了解过的朋友们应该都知道SEO必不可少的工作之一就是查询关键词的搜索排名。关键词少的时候可以一个一个去查没什么问题,但是到了后期,一个网站都有几百上千的关键词,你再去一个一个查,至少要花费数小时的时间。 虽然市面上有很多SEO免费或者收费工具,但免费的基本都不能批量查,网上免费的最多也就只能10个10个查询,而且查询速度很慢。收费的工具如Ahrefs、SEMrush等以月为单位收费最低也都要上百美刀/月,当然如果觉得价格合适也可以进行购买,毕竟这些工具的很多功能都很实用。今天我给大家分享的这个排名搜索工具基于python实现,当然肯定
39 0
|
25天前
|
XML Shell Linux
性能工具之 JMeter 使用 Python 脚本快速执行
性能工具之 JMeter 使用 Python 脚本快速执行
40 1
性能工具之 JMeter 使用 Python 脚本快速执行
|
25天前
|
数据可视化 数据挖掘 Python
Python中的数据可视化工具Matplotlib简介与实践
在本文中,我们将介绍Python中常用的数据可视化工具Matplotlib,包括其基本概念、常用功能以及实际应用。通过学习Matplotlib,读者可以更好地理解和运用数据可视化技术,提升数据分析与展示的能力。
|
29天前
|
Web App开发 前端开发 JavaScript
Python Selenium是一个强大的自动化测试工具
Python Selenium是一个强大的自动化测试工具

热门文章

最新文章