图表部分,很多要记忆的。以下来自于培训材料的记录。

但我个人觉得更重要的是要根据业务特点确定用什么样的图表,然后再去查具体的参数,光记住参数意义不是很大。

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

一、数据读取

data = pd.read_csv('文件名.csv',engine = 'python',encoding = 'utf-8')

二、绘制图表

1、 Series直接生成图表

plt.plot(data)         #index为横坐标,value为纵坐标

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

ts = ts.cumsum()
ts.plot(kind='line',   #kind → line,bar,barh...(折线图,柱状图,柱状图-横...)
label = 'hehe',        # label → 图例标签,Dataframe格式以列名为label
style = '--g.',        # style → 风格字符串,linestyle(-),marker(.),color(g)
color = 'red',
alpha = 0.4,           # alpha → 透明度,0-1
use_index = True,      # use_index → 将索引用为刻度标签,默认为True
rot = 45,              # rot → 旋转刻度标签,0-360
grid = True,           # grid → 显示网格,一般直接用plt.grid
ylim = [-50,50],       # xlim,ylim → x,y轴界限
yticks = list(range(-50,50,10)),# xticks,yticks → x,y轴刻度值
figsize = (8,4),       # figsize → 图像大小
title = 'test',        # title → 图名
legend = True)         # legend → 是否显示图例,一般直接用plt.legend()
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x') # 网格
plt.legend()

2、Dataframe直接生成图表

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(kind='line',
style = '--.',
alpha = 0.4,
use_index = True,
rot = 45,
grid = True,
figsize = (8,4),
title = 'test',
legend = True,
subplots = False,
colormap = 'Greens')
# subplots → 是否将各个列绘制到不同图表,默认False
# 也可以 → plt.plot(df)

3、柱状图与堆叠图

fig,axes = plt.subplots(4,1,figsize = (10,10))
s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])

s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0]) # ax参数 → 选择第几个子图
# 单系列柱状图方法一:plt.plot(kind='bar/barh')

df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])
df.plot(kind='bar',ax = axes[1],grid = True,colormap='Reds_r')
# 多系列柱状图

df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True)
# 多系列堆叠图
# stacked → 堆叠

df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
# 新版本plt.plot.<kind>

4、 柱状图 plt.bar()

plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)

plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)
# x,y参数:x,y值
# width:宽度比例
# facecolor柱状图里填充的颜色、edgecolor是边框的颜色
# left-每个柱x轴左边界,bottom-每个柱y轴下边界 → bottom扩展即可化为甘特图 Gantt Chart
# align:决定整个bar图分布,默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
# xerr/yerr :x/y方向error bar

5、面积图

fig,axes = plt.subplots(2,1,figsize = (8,6))
df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])

df1.plot.area(colormap = 'Greens_r',alpha = 0.5,ax = axes[0])
df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])
# 使用Series.plot.area()和DataFrame.plot.area()创建面积图
# stacked:是否堆叠,默认情况下,区域图被堆叠
# 为了产生堆积面积图,每列必须是正值或全部负值!
# 当数据有NaN时候,自动填充0,所以图标签需要清洗掉缺失值

6、饼图 plt.pie()
# plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
# radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)

s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
plt.axis('equal') # 保证长宽相等
plt.pie(s,
explode = [0.1,0,0,0],            指定每部分的偏移量
labels = s.index,
colors=['r', 'g', 'b', 'c'],
autopct='%.2f%%',               #饼图上的数据标签显示方式
pctdistance=0.6,                #每个饼切片的中心和通过autopct生成的文本开始之间的比例
labeldistance = 1.2,            #被画饼标记的直径,默认值:1.1
shadow = True,                  #阴影
startangle=0,                   #开始角度
radius=1.5,                     #半径
frame=False)                    #图框
print(s)

# counterclock:指定指针方向,顺时针或者逆时针

7、直方图+密度图

s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,
histtype = 'bar',
align = 'mid',
orientation = 'vertical',
alpha=0.5,
normed =True)
# bin:箱子的宽度
# normed 标准化
# histtype 风格,bar,barstacked,step,stepfilled
# orientation 水平还是垂直{‘horizontal’, ‘vertical’}
# align : {‘left’, ‘mid’, ‘right’}, optional(对齐方式)

s.plot(kind='kde',style='k--')
# 密度图

8、堆叠直方图

plt.figure(num=1)
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2},
columns=['a', 'b', 'c','d'])
df.plot.hist(stacked=True,
bins=20,
colormap='Greens_r',
alpha=0.5,
grid=True)
# 使用DataFrame.plot.hist()和Series.plot.hist()方法绘制
# stacked:是否堆叠

df.hist(bins=50)
# 生成多个直方图

9、散点图

# plt.scatter()散点图
# plt.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None,
# alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)

plt.figure(figsize=(8,6))
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y,marker='.',
s = np.random.randn(1000)*100,
cmap = 'Reds',
c = y,
alpha = 0.8,)
plt.grid()
# s:散点的大小
# c:散点的颜色
# vmin,vmax:亮度设置,标量
# cmap:colormap

10、散点矩阵

# pd.scatter_matrix()
# pd.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None,
# grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds)

df = pd.DataFrame(np.random.randn(100,4),columns = ['a','b','c','d'])
pd.scatter_matrix(df,figsize=(10,6),
marker = 'o',
diagonal='kde',
alpha = 0.5,
range_padding=0.1)
# diagonal:({‘hist’, ‘kde’}),必须且只能在{‘hist’, ‘kde’}中选择1个 → 每个指标的频率图
# range_padding:(float, 可选),图像在x轴、y轴原点附近的留白(padding),该值越大,留白距离越大,图像远离坐标原点

11、创建极坐标轴

s = pd.Series(np.arange(20))
theta=np.arange(0,2*np.pi,0.02)
print(s.head())
print(theta[:10])
# 创建数据

fig = plt.figure(figsize=(8,4))
ax1 = plt.subplot(121, projection = 'polar')
ax2 = plt.subplot(122)
# 创建极坐标子图
# 还可以写:ax = fig.add_subplot(111,polar=True)

ax1.plot(theta,theta*3,linestyle = '--',lw=1)
ax1.plot(s, linestyle = '--', marker = '.',lw=2)
ax2.plot(theta,theta*3,linestyle = '--',lw=1)
ax2.plot(s)
plt.grid()
# 创建极坐标图,参数1为角度(弧度制),参数2为value
# lw → 线宽

# 极坐标参数设置

theta=np.arange(0,2*np.pi,0.02)
plt.figure(figsize=(8,4))
ax1= plt.subplot(121, projection='polar')
ax2= plt.subplot(122, projection='polar')
ax1.plot(theta,theta/6,'--',lw=2)
ax2.plot(theta,theta/6,'--',lw=2)
# 创建极坐标子图ax

ax2.set_theta_direction(-1)
# set_theta_direction():坐标轴正方向,默认逆时针

ax2.set_thetagrids(np.arange(0.0, 360.0, 90),['a','b','c','d'])
ax2.set_rgrids(np.arange(0.2,2,0.4))
# set_thetagrids():设置极坐标角度网格线显示及标签 → 网格和标签数量一致
# set_rgrids():设置极径网格线显示,其中参数必须是正数

ax2.set_theta_offset(np.pi/2)
# set_theta_offset():设置角度偏移,逆时针,弧度制

ax2.set_rlim(0.2,1.2)
ax2.set_rmax(2)
ax2.set_rticks(np.arange(0.1, 1.5, 0.2))
# set_rlim():设置显示的极径范围
# set_rmax():设置显示的极径最大值
# set_rticks():设置极径网格线的显示范围

12、雷达图1 - 极坐标的折线图/填图 - plt.plot()

plt.figure(figsize=(8,4))

ax1= plt.subplot(111, projection='polar')
ax1.set_title('radar map\n') # 创建标题
ax1.set_rlim(0,12)

data1 = np.random.randint(1,10,10)
data2 = np.random.randint(1,10,10)
data3 = np.random.randint(1,10,10)
theta=np.arange(0,2*np.pi,2*np.pi/10)
# 创建数据

ax1.plot(theta,data1,'.--',label='data1')
ax1.fill(theta,data1,alpha=0.2)
ax1.plot(theta,data2,'.--',label='data2')
ax1.fill(theta,data2,alpha=0.2)
ax1.plot(theta,data3,'.--',label='data3')
ax1.fill(theta,data3,alpha=0.2)
# 绘制雷达线

# 雷达图2 - 极坐标的折线图/填图 - plt.polar()
# 首尾闭合

labels = np.array(['a','b','c','d','e','f']) # 标签
dataLenth = 6 # 数据长度
data1 = np.random.randint(0,10,6)
data2 = np.random.randint(0,10,6) # 数据

angles = np.linspace(0, 2*np.pi, dataLenth, endpoint=False) # 分割圆周长
data1 = np.concatenate((data1, [data1[0]])) # 闭合
data2 = np.concatenate((data2, [data2[0]])) # 闭合
angles = np.concatenate((angles, [angles[0]])) # 闭合

plt.polar(angles, data1, 'o-', linewidth=1) #做极坐标系
plt.fill(angles, data1, alpha=0.25)# 填充
plt.polar(angles, data2, 'o-', linewidth=1) #做极坐标系
plt.fill(angles, data2, alpha=0.25)# 填充

plt.thetagrids(angles * 180/np.pi, labels) # 设置网格、标签
plt.ylim(0,10) # polar的极值设置为ylim

13、极轴图 - 极坐标的柱状图

plt.figure(figsize=(8,4))

ax1= plt.subplot(111, projection='polar')
ax1.set_title('radar map\n') # 创建标题
ax1.set_rlim(0,12)

data = np.random.randint(1,10,10)
theta=np.arange(0,2*np.pi,2*np.pi/10)
# 创建数据

bar = ax1.bar(theta,data,alpha=0.5)
for r,bar in zip(data, bar):
bar.set_facecolor(plt.cm.jet(r/10.)) # 设置颜色
plt.thetagrids(np.arange(0.0, 360.0, 90), []) # 设置网格、标签(这里是空标签,则不显示内容)

14、箱型图

# plt.plot.box()绘制

fig,axes = plt.subplots(2,1,figsize=(10,6))
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
# 箱型图着色
# boxes → 箱线
# whiskers → 分位数与error bar横线之间竖线的颜色
# medians → 中位数线颜色
# caps → error bar横线颜色

df.plot.box(ylim=[0,1.2],
grid = True,
color = color,
ax = axes[0])
# color:样式填充

df.plot.box(vert=False,
positions=[1, 4, 5, 6, 8],
ax = axes[1],
grid = True,
color = color)
# vert:是否垂直,默认True
# position:箱型图占位

Python学习笔记四:主要图表的更多相关文章

  1. Python学习笔记(四)Python函数的参数

    Python的函数除了正常使用的必选参数外,还可以使用默认参数.可变参数和关键字参数. 默认参数 基本使用 默认参数就是可以给特定的参数设置一个默认值,调用函数时,有默认值得参数可以不进行赋值,如: ...

  2. Python学习笔记四

    一.装饰器 1.知识储备 函数对象 函数可以被引用 函数可以当参数传递 返回值可以是函数 可以当作容器的元素 def func1(): print (666) def func2(): print ( ...

  3. Python学习笔记四:面向对象编程

    一:定义类并创建实例 Python中定义类,通过class关键字,类名开头大写,参数列表为所继承的父类.如果没有需要明确继承的类,则继承object. 使用类来创建对象,只需 类名+() 形式即可,p ...

  4. python学习笔记(四) 思考和准备

    一.zip的坑 zip()函数接收多个可迭代数列,将数列中的元素重新组合,在3.0中返回迭代器指向 数列首地址,在3.0以下版本返回List类型的列表数列.我用的是3.5版本python, 所以zip ...

  5. python学习笔记(四):函数

    一.函数是什么? 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,编程中的函数在英文中也有很多不同的叫法.在BASIC中叫做subroutine(子过程或子程序),在Pasc ...

  6. python学习笔记(四):生成器、内置函数、json

    一.生成器 生成器是什么?其实和list差不多,只不过list生成的时候数据已经在内存里面了,而生成器中生成的数据是当被调用时才生成呢,这样就节省了内存空间. 1. 列表生成式,在第二篇博客里面我写了 ...

  7. 【Python学习笔记四】获取html内容之后,如何提取信息:使用正则表达式筛选

    在能够获取到网页内容之后,发现内容很多,那么下一步要做信息的筛选,就和之前的筛选图片那样 而在python中可以通过正则表达式去筛选自己想要的数据 1.首先分析页面内容信息,确定正则表达式.例如想获取 ...

  8. python学习笔记四 迭代器,生成器,装饰器(基础篇)

    迭代器 __iter__方法返回一个迭代器,它是具有__next__方法的对象.在调用__next__方法时,迭代器会返回它的下一个值,若__next__方法调用迭代器 没有值返回,就会引发一个Sto ...

  9. Python学习笔记四--字典与集合

    字典是Python中唯一的映射类型.所谓映射即指该数据类型包含哈希值(key)和与之对应的值(value)的序列.字典是可变类型.字典中的数据是无序排列的. 4.1.1字典的创建及赋值 dict1={ ...

随机推荐

  1. nethogs-linux程序网络使用情况

    netthogs可以显示每个程序的网络传输情况安装nethogs工具yum install https://mirrors.tuna.tsinghua.edu.cn/epel/7/x86_64/Pac ...

  2. php页面传递参数值几种方法总结

    2013-06-06 18:02 (分类:) 又搞了一个学期的php,就这样吧. php是一种服务器的脚本语言,他也是现在最为流行的WEB开发语言,下面我们来讲述一下几种上在php开发应用中常用的四种 ...

  3. springboot 基于Tomcate的自启动流程

    Springboot 内置了Tomcat的容器,我们今天来说一下Springboot的自启动流程. 一.Spring通过注解导入Bean大体可分为四种方式,我们主要来说以下Import的两种实现方法: ...

  4. H5页面优化

    1. 页面优化 优化内容: 提升网页响应速度:减少请求,文件大小,页面性能 对搜索引擎,屏幕阅读器友好: 提高可读性,可维护性:规范代码 优化操作: 减少请求:小图标使用sprite拼图合并为一个图片 ...

  5. 杭电-------2041超级楼梯(c语言写)

    /* 当未走的楼梯大于1时,可以选择走一步或者走两步,每次所做的选择相似, 符合分治法的特性,因此选择分治法,又测试用例有多组,为了避免多组 用例的重复计算,可用一个数组将已经知道的剩下的楼梯可以走的 ...

  6. PHP关于mb_substr不能起作用的问题

    mb_substr不能起作用最大的原因是因为没有在php.ini文件没有把 ;extension=mbstring 前面的 :号去掉

  7. get、post请求参数乱码解决方法(qq:1324981084)

    java高级架构师全套vip教学视频,需要的加我qq1324981084 在实际的项目中我们会遇见中文乱码的问题,这个问题是很恶心的事,所以我在这里提供了一些解决中文乱码的方法,希望能给大家一些帮助. ...

  8. java之时间戳处理

    ●时间戳(timestamp)定义 时间戳指的是从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数.严格来说,不管你处在地球上的哪个地方,任意时间点的时间戳都是相同的.这点有利于线 ...

  9. Python——20200220Python123冲刺试卷 - 1

    知识点:面向对象继承,数组组织,文件操作,数据类型 1.面向对象的继承:继承是指类之间共享属性和操作的性质 2.软件危机的原因不包括:软件成本不断提高 软件危机原因: 软件开发生产率低.软件过程不规范 ...

  10. Spring Bean自动装配有哪些方式?

    Spring 容器能够自动装配 Bean .也就是说,可以通过检查 BeanFactory 的内容让 Spring 自动解析 Bean 的协作者. 自动装配的不同模式: no - 这是默认设置,表示没 ...