Notes_matplotlib_连续线和散点图

matplotlib连续图和散点图的笔记

  • 使用jupyter notebook
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
x=np.linspace(0,10,500)
fig=plt.figure()
plt.plot(x,np.sin(x))
[<matplotlib.lines.Line2D at 0x1ca9ae42610>]

在这里插入图片描述

fig.savefig('fig_save.png')
from IPython.display import Image
Image('fig_save.png')

在这里插入图片描述

fig.canvas.get_supported_filetypes()#支持的图片格式
{'ps': 'Postscript',
 'eps': 'Encapsulated Postscript',
 'pdf': 'Portable Document Format',
 'pgf': 'PGF code for LaTeX',
 'png': 'Portable Network Graphics',
 'raw': 'Raw RGBA bitmap',
 'rgba': 'Raw RGBA bitmap',
 'svg': 'Scalable Vector Graphics',
 'svgz': 'Scalable Vector Graphics'}
plt.style.use('seaborn-whitegrid')#设置风格。
fig=plt.figure()
ax=plt.axes()
x=np.linspace(0,10,1000)
ax.plot(x,np.sin(x))
ax.plot(x,np.cos(x),color='m')
#plt.xlim(-1,10)
#或者用plt.plot(x,np.sin(x))
[<matplotlib.lines.Line2D at 0x1ca9aea4340>]

在这里插入图片描述

fig(plt.Figure 类的一个实例)可以被看成是一个能够容纳各种坐标轴、图形、文字和标签的容器。
ax(plt.Axes 类的一个实例)是一个带有刻度和标签的矩形(暂且看做坐标轴),最终会包含所有可视化的图形元素。
在这里也更好的理解了np.linspace()的实际意义。

plt.plot(x-1,np.sin(x),'--g',linestyle='-',label='sinx')
plt.xlim(-10,10)
plt.ylim(-1,1)
#调整x,y的坐标轴,可以逆序如:plt.xlim(10,-1)
#同plt.axis([xmin,xmax,ymin,ymax])
#同ax.axis([xmin,xmax,ymin,ymax])
plt.title('sinx',loc='left')
#pad同下面的labelpad,loc设置位置['left','center','right']
plt.xlabel('x',labelpad=10)
#labelpad设置标签到轴的距离
plt.ylabel('sinx')
plt.axis('tight')#使图像和坐标适配
plt.axis('on')#开始x,y标签和坐标线
(-1.5, 9.5, -1.0999971452300779, 1.099999549246729)

在这里插入图片描述

  • color:
    1. 标准颜色名称
    2. RGB元组,范围在0~1
    3. 0~1范围内的灰度值
    4. HTML颜色名
    5. 缩写颜色代码(rgbcmykw):Red,Green,Blue,Cyan(青色),Magenta(品红),Yellow(黄),BlacK(黑)White
    6. 十六进制
  • linestyle:
    1. ‘solid’,即’-’,实线
    2. ‘dashed’,即’–'虚线
    3. ‘dashdot’,即’-.'点划线
    4. ‘dotted’,即’:'实点线
  • 也可将颜色缩写和linestyle合在一起,如:’–g’绿色实线’k–‘黑色实线,不能用color=’–g’.

plt.plot()中对于线性控制等参数太多,要用时再去看docstring。
== 连续图和散点图其实是一样的 ==,如:‘o’是散点图,’-‘是连续图,’-o’是连续散点图。
plt.axes()的实例ax.plot的docstring和plt.plot 的docstring好像是同一个.
plt.plot()返回line的对象列表》

x=np.linspace(1,10,20)
plt.plot(x,'-mo',label='line 1',linewidth=0.5,alpha=0.5,marker='^')
#注意,这里的x实际上被画成了y。因为参数x是可以选,默认为range(len(y)).
#alpha 是透明度。0~1
#label是图例,绘制图例要使用plt.legend()
#marker是图形'--mo'中已经对marker进行了设定和后面的marker='^'冲突。以关键字实参为准。
plt.legend()#绘制图例。
<matplotlib.legend.Legend at 0x1ca9af8bb80>

在这里插入图片描述

Matplotlib 陷阱

虽然绝大多数plt 函数都可以直接转换成 ax 方法(例如 plt.plot() → ax.plot()、
plt.legend() → ax.legend() 等),但是== 并非所有 ==的命令都可以这样用。尤其是用来设
置坐标轴上下限、坐标轴标题和图形标题的函数,它们大都稍有差别。一些 MATLAB
风格的方法和面向对象方法的转换如下所示:
plt.xlabel() → ax.set_xlabel()
plt.ylabel() → ax.set_ylabel()
plt.xlim() → ax.set_xlim()
plt.ylim() → ax.set_ylim()
plt.title() → ax.set_title()
== 不要写成plt.xlim=(),会覆盖函数名,导致意想不到的错误,可以重启jupyter notebook 的kernel解决 ==
在用面向对象接口画图时,不需要单独调用这些函数,通常采用 ax.set() 方法一次性
设置所有的属性是更简便的方法:
ax = plt.axes() ax.plot(x, np.sin(x)) ax.set(xlim=(0, 10), ylim=(-2, 2),xlabel='x', ylabel='sin(x)', title='A Simple Plot')
——摘自《python数据科学手册》[美] Jake VanderPlas

散点图

markerlist=['.',',','o','v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','|','_']
for marker in markerlist:
    plt.plot(np.random.rand(5),np.random.rand(5),marker,label="marker='%s'"%marker)
    plt.axis('tight')
    plt.legend(numpoints=1)

在这里插入图片描述

plt.plot(x,np.sin(x),'--bH',
        markersize=15,#ms
        markerfacecolor='m',#mfc
        markeredgecolor='c',#mec
        markeredgewidth=3,)#mew
[<matplotlib.lines.Line2D at 0x1ca9b2d2df0>]

在这里插入图片描述

df=pd.DataFrame(np.random.randn(5,2),columns=['A','K'],index=range(5))
df=df.reset_index()
df
indexAK
000.459251-2.682857
11-0.194248-0.879362
22-1.818532-0.278777
331.797815-0.339322
440.368426-0.262445
plt.plot('index','A','K',marker='x',data=df)
#向data传递有索引的数据如:dict,DataFrame,numpy结构化数组
#就可以使用索引名,但不允许用fmt设置格式,只能用关键字实参。
#这里的'index'设置了x轴
#只能统一设置图形。
[<matplotlib.lines.Line2D at 0x1ca9d1ee880>,
 <matplotlib.lines.Line2D at 0x1ca9d1c6910>]

在这里插入图片描述

plt.plot(df['index'],df['A'],'--g',df['K'],'-x')
#还可以使用切片,这里的可用格式:
#plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs):
#plot(a,b)解读为x,y,plot(a,b,c)解读为x,y,y2.
#注意这种格式和data参数相斥。
[<matplotlib.lines.Line2D at 0x1ca9d4eea00>,
 <matplotlib.lines.Line2D at 0x1ca9d4fa9a0>]

在这里插入图片描述

s=np.linspace(-2,2,1000)
y=np.sqrt(1-(np.abs(s)-1)**2)
z=np.arccos(1-np.abs(s))-np.pi
plt.plot(y,"-m",z,'-c')
#心形线。
[<matplotlib.lines.Line2D at 0x1ca9d61f460>,
 <matplotlib.lines.Line2D at 0x1ca9d61f340>]

在这里插入图片描述

plt.scatter(x,np.sin(x),marker='v')#不允许用线性'-'等。
<matplotlib.collections.PathCollection at 0x1ca9d9493a0>

在这里插入图片描述

rng=np.random.RandomState(42)
x=rng.randn(100)
y=rng.randn(100)
colors=rng.rand(100)
sizes=1000*rng.rand(100)
plt.scatter(x,y,c=colors,s=sizes,alpha=0.3,cmap='viridis')
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x1ca9d69b250>

在这里插入图片描述

plt.scatter([1,2,3],[1,2,3],s=500,c=['b','m','y'],marker='^',edgecolors='m',linewidth=2)
<matplotlib.collections.PathCollection at 0x1ca9f0d86d0>

在这里插入图片描述

plt.scatter([[1,2,3],[0.5,1.5,2.5]],
            [[1,2,3],[0.5,1.5,2.5]],
            c=[[1,7,3],[3,2,9]],cmap='viridis')
<matplotlib.collections.PathCollection at 0x1caa0341100>

在这里插入图片描述

plt.scatter(x,y,c,s,marker,cmap,linewidths,alpha,edgecolors,data)

  • c:color,可以是’g’,也可以是颜色格式字符串序列,也可以是数序列(这时要用cmap指定数向颜色映射
  • s:marker 的大小
  • cmap上面提到了
  • marker指定形状
  • linewidths指定marker边框线大小,这里的数字代表的含义与s中不同,如:25代表的大小linewidths远比s大,像素?
  • edgecolors指定marker边框线颜色,可选’face’
  • alpha为透明度:0为透明。0~1.
  • x,y,c,s都是一维数组,二维会被转为一维。最好,这几个都是同形状
  • x,y,c,s都可是masked array,使用numpy.ma模块?。
  • data参数的用法同plt.plot,示例如下:

plt.colorbar()是颜色线条参考。
plt.scatter()plt.plot()相比,可对每个点的属性等指定,但在面对大量数据时,效率不够高,内存消耗大。

data2=pd.DataFrame({'lx':[1,2,3,4,5],
                   'ly':[1,2,3,4,5],
                   'colors':[2,3,4,1,4],
                   'size':[23,45,12,60,34]})
plt.scatter('lx','ly',c='colors',s='size',cmap='viridis',data=data2)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x1caa0581a60>

在这里插入图片描述

from sklearn.datasets import load_iris
iris=load_iris()
features=iris['data'].T
sepal_length=features[0]#花萼长度
sepal_width=features[1]#花萼宽度
pedal_width=features[3]#花瓣宽度
plt.scatter(sepal_length,sepal_width,
            s=100*pedal_width,
            alpha=0.3,
            c=iris.target,
            cmap='viridis')
plt.xlabel('sepal length(cm)')
plt.ylabel('sepal width(cm)')
plt.colorbar()
#使用颜色代表花色,大小代表花瓣宽度,
#x,y分别代表花萼长度宽度。
<matplotlib.colorbar.Colorbar at 0x18a671eb7c0>

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值