图与图表——Matplotlib学习笔记(一)


一、matplotlib

matplotlib是一个绘图库,创建的图形美化方面比较完善,可以自定义线条的颜色和样式,可以在一张绘图纸上绘制多张小图,也可以在一张图上绘制多条线,可以很方便地将数据可视化并对比分析。

import matplotlib.pyplot as plt
# 第一步创建画布
plt.figure(figsize=(20,8), dpi=400)
# 第二步绘制图像
x = [1,2,3,4,5,6]
y = [a,b,c,d,e,f]
plt.plot(x, y)
# 3.显示图像
plt.show()

请添加图片描述


二、条形图

常用的条形图包括垂直图,水平图,堆积图和分组图

2.1简单绘制:

1、样式介绍

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[1,4,9,16,25])
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel')
plt.show()

注释:
第三行中引号部分的xlabel是对于x轴的名称命名,fontsize是对于字体大小的改变

import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.plot([1,2,3,4,5],[1,4,9,16,25],'--',color = 'r')
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel')
plt.show()

与上一个图不同的是在第三行中加入了对于线条的改变,这样打印出来的图像将会是由虚线构成。
color是对于线条颜色的选择
同时将第三行组合:
plt.plot([1,2,3,4,5],[1,4,9,16,25],‘r-’)
在第二行中加入图表风格,按需选择就阔以了。

线条样式:

符号线条呈现的样式
无符号实线
‘- -’虚线
’ : ’点线
’ -. ’虚点线
’ , ’像素点
’ s ’正方点
’ * ’星形点

线条颜色:

符号对应颜色
’ r ’红色
’ b ’蓝色
’ g ’绿色
’ c ’青色
’ y ’黄色
’ k ’黑色
'w ’白色

2、简单图表绘制

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
np.random.seed(0)#取相同的seed,使得生成的随机数相同
x = np.arange(5)
y = np.random.randint(-5,5,5)#在-5到5之间选取5个数
print(y)
fig,axes = plt.subplots(ncols = 2)
v_bars = axes[0].bar(x,y,color='r')#纵轴
h_bars = axes[1].barh(x,y,color='g')#横轴
#给图表加上横线
axes[0].axhline(0,color='grey',linewidth=2)
axes[1].axvline(0,color='grey',linewidth=2)
plt.show()

图像:
请添加图片描述

2.2按照条件将图表划分

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5,5,5)
fig,ax = plt.subplots()
v_bars = ax.bar(x,y,color='lightblue')#默认线条都为浅蓝色
for bar,height in zip(v_bars,y):#将条形图和y值进行遍历,将小于0图形改为黄色
    if height<0:
        bar.set(edgecolor = 'b',color ='y',linewidth=3)
plt.show()

图像:
请添加图片描述

2.3将图表填充

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
x = np.random.randn(100).cumsum()#cumsum是对其进行求和
y = np.linspace(0,20,100)#在0到20之间找100个数
fig,ax = plt.subplots()
ax.fill_between(x,y,color = 'lightblue')#将画出的图像进行填充
plt.show()

图像:
请添加图片描述

2.4、书上展示的代码:

import matplotlib.pyplot as plt
plt.style.use('ggplot')#这里我使用的是ggplot风格
customers = ['ABC','DEF','GHI','JKL','MNO']#横轴
customers_index = range(len(customers))
sale_amounts = [127,90,201,111,232]
fig = plt.figure()
#添加一个子图1,1,1表示创建一个一行一列的子图
ax1 = fig.add_subplot(1,1,1)
#customers_index设置条形左侧在x轴上的坐标,sale_amounts设置条形的高度,align='center'设置条形与标签中间对齐,color即为设置颜色。
ax1.bar(customers_index,sale_amounts,align='center',color='darkblue')
#设置刻度线位置在x轴底部和y轴左侧,使图形的上部和右侧不显示刻度线
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
#rotation=0表示刻度标签是水平的,fontsize = 'small'将刻度标签的字体设为小字体
plt.xticks(customers_index,customers,rotation=0,fontsize = 'small')
plt.xlabel('Custmoer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')
#dpi=400设置图形分辨率,bbox_inches = 'tight'表示保存图片时,将四周的空白去掉
plt.savefig('bar_plot.png',dpi=400,bbox_inches = 'tight')
plt.show()

请添加图片描述

三、散点图

主要特点是:研究两个变量的相关性,大体分为三种,正相关,负相关,不相关

3.1、简单绘制:

1、写一个简单的身高体重的散点图

import numpy as np
import matplotlib.pyplot as plt
height = [161,170,198,188,156,185,165]
weight = [50,65,67,85,55,66,69]
plt.scatter(height,weight)
plt.show()

请添加图片描述

2、正相关的散点图

import numpy as np
import matplotlib.pyplot as plt
N=100
X = np.random.randn(N)
Y = X+np.random.randn(N)*0.5
plt.scatter(X,Y)
plt.show()

scatter函数使用方法:
scatter_(input, dim, index, src):将src中数据根据index中的索引按照dim的方向填进input。可以理解成放置元素或者修改元素 。
有图像可知:整体向上排列,说明x,y呈现正相关
请添加图片描述

3、负相关

如上所述只需要改变第五行的代码

import numpy as np
import matplotlib.pyplot as plt
N=100
X = np.random.randn(N)
Y = -X+np.random.randn(N)*0.5#只需要改变这里!!!
plt.scatter(X,Y)
plt.show()

图像:
请添加图片描述

3.2、书上展示的代码:

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
x = np.arange(start = 1,stop = 15,step = 1)
y_linear = x+5 * np.random.randn(14)
y_quadratic = x**2 + 10*np.random.randn(14)
fn_linear = np.poly1d(np.polyfit(x,y_linear,deg=1))
fn_quadratic = np.poly1d(np.polyfit(x,y_quadratic,deg=2))
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x,y_linear,'bo',x,y_quadratic,'go',x,fn_quadratic(x),'g-',linewidth=2)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Scatter Plots Regression Lines')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.xlim((min(x)-1,max(x)+1))
plt.ylim((min(y_quadratic)-10,max(y_quadratic)+10))
plt.savefig('scatter_plot.png',dpi=400,bbox_inches='tight')
plt.show()

图像:
请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

被窝探险家104

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值