大三上学习笔记2

Matplotlib绘图02

import matplotlib.pyplot as plt # 导入模块matplotlib.pyplot
%matplotlib inline
import numpy as np
plt.rcParams[‘font.sans-serif’]=[‘SimHei’]#用来正常显示中文标签
plt.rcParams[‘axes.unicode_minus’]=False #用来正常显示负号

x = np.linspace(0.05,10,1000) #在0.05~10之间等间隔取1000个数
y = np.sin(x)

plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x15a1d8ebcc0>]

plt.gcf( )与plt.gca()
当前的图表和子图可以使用pli.gcf()和plt.gca0获得,分别表示Get Current Figure和Get Current Axes.在pyplot模块中,许多函数都是对当前的Figure或Axes对象进行处理,比如说:plt.pot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。

plt.plot(x,y)
ax = plt.gca()
ax.spines[“right”].set_color(‘red’)

plt.plot(x,y)
ax = plt.gca()
ax.spines[“right”].set_color(‘red’)
ax.spines[“left”].set_color(‘green’)
ax.spines[“top”].set_color(‘yellow’)
ax.spines[“bottom”].set_color(‘orange’)

plt.plot(x,y)
ax = plt.gca()
ax.spines[“right”].set_color(‘none’)
ax.spines[“left”].set_color(‘none’)
ax.spines[“top”].set_color(‘none’)
ax.spines[“bottom”].set_color(‘none’)

x = np.linspace(-3.15,3.15,100)
y = np.sin(x)
plt.plot(x,y)
ax = plt.gca()
ax.spines[“right”].set_color(‘none’)
ax.spines[“top”].set_color(‘none’)

#把x轴的刻度设为bottom
#把y轴的刻度设为left
ax.xaxis.set_ticks_position(‘bottom’)
ax.yaxis.set_ticks_position(‘left’)

#设置bottom对应到0点
#设置left对应到0点
ax.spines[‘bottom’].set_position((‘data’,0))
ax.spines[‘left’].set_position((‘data’,0))

plt.figure() 创建Figure对象
Figure对象是后续绘图操作的总容器。
如果不创建Figure对象,直接调用接下来的plot()进行绘图,matplotlib会自动创建一个Figure对象。
但事先创建Figure对象可以对它进行更精细地设定。

help(plt.figure)
Help on function figure in module matplotlib.pyplot:

figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, **kwargs)
Creates a new figure.

Parameters
----------

num : integer or string, optional, default: none
    If not provided, a new figure will be created, and the figure number
    will be incremented. The figure objects holds this number in a `number`
    attribute.
    If num is provided, and a figure with this id already exists, make
    it active, and returns a reference to it. If this figure does not
    exists, create it and returns it.
    If num is a string, the window title will be set to this figure's
    `num`.

figsize : tuple of integers, optional, default: None
    width, height in inches. If not provided, defaults to rc
    figure.figsize.

dpi : integer, optional, default: None
    resolution of the figure. If not provided, defaults to rc figure.dpi.

facecolor :
    the background color. If not provided, defaults to rc figure.facecolor

edgecolor :
    the border color. If not provided, defaults to rc figure.edgecolor

Returns
-------
figure : Figure
    The Figure instance returned will also be passed to new_figure_manager
    in the backends, which allows to hook custom Figure classes into the
    pylab interface. Additional kwargs will be passed to the figure init
    function.

Notes
-----
If you are creating many figures, make sure you explicitly call "close"
on the figures you are not using, because this will enable pylab
to properly clean up the memory.

rcParams defines the default values, which can be modified in the
matplotlibrc file

plt.figure(‘aa’,dpi=600)
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x15a1d9628d0>]

plt.figure(“baobei01”,figsize=(5,3),dpi=300,facecolor=“g”,edgecolor=“red”)
plt.plot(x,y)
plt.title(“dpi300”)
<matplotlib.text.Text at 0x15a1c2ad358>

plt.savefig()

plt.plot(x,y)
ax = plt.gca()
ax.spines[“right”].set_color(‘red’)
ax.spines[“left”].set_color(‘green’)
ax.spines[“top”].set_color(‘yellow’)
ax.spines[“bottom”].set_color(‘orange’)
plt.savefig(“D:\myfig_01.jpg”)

plt.bar()与plt.barh()

x = np.arange(10)
#生成10个1到10之间的整数
data = np.random.randint(1,11,10)
data
array([1, 2, 1, 6, 2, 3, 8, 5, 3, 3])

plt.bar(x,data)
plt.show()

#水平条形图
plt.barh(x,data,label=‘bar’)
plt.legend(loc=1)
plt.title(‘horizontal bar chart’)
plt.show()

#绘制条形图
plt.bar(x,data,facecolor=“g”,edgecolor=“r”)
<Container object of 10 artists>

#绘制条形图
plt.bar(x,data,facecolor=“g”,edgecolor=“r”,lw=3)
<Container object of 10 artists>

#绘制条形图
plt.bar(x,data,facecolor=“g”,edgecolor=“r”,lw=3,alpha=0.3)
<Container object of 10 artists>

#绘制条形图
plt.bar(x,-data,facecolor=“g”,edgecolor=“r”,hatch=’/’,lw=3,alpha=0.7)
<Container object of 10 artists>

#绘制条形图
plt.bar(x,data,facecolor=“g”,edgecolor=“r”,hatch=’/’,tick_label=[‘一’,‘二’,‘三’,‘四’,‘五’,‘六’,‘七’,‘八’,‘九’,‘十’],lw=3,alpha=0.7)
<Container object of 10 artists>

#多序列条形图
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
index = np.arange(5)
data1 = [3,4,6,8,9]
data2 = [11,23,6,5,1]
data3 = [12,6,21,8,26]
#把一个空间分3为部分,定义a值为0.3,三个占0.9,剩0.1的空格
a = 0.3
plt.title(‘multi bar chart’)
plt.bar(index,data1,a,color=‘r’,label=‘a’)
plt.bar(index+a,data2,a,color=‘b’,label=‘b’)
plt.bar(index+2*a,data3,a,color=‘g’,label=‘c’)
plt.legend(loc=2)
plt.show()

#多序列条形图转换为堆积条形图
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
index = np.arange(5)
data1 = [3,4,6,8,9]
data2 = [11,23,6,5,1]
data3 = [12,6,21,8,26]
#把一个空间分3为部分,定义a值为0.3,三个占0.9,剩0.1的空格
a = 0.3
plt.bar(index,data1,color=‘r’,label=‘a’)
plt.bar(index+a,data2,bottom=data1,color=‘b’,label=‘b’)
plt.bar(index+2*a,data3,bottom=(data2+data1),color=‘g’,label=‘c’)
plt.legend(loc=2)
plt.show()

ValueError Traceback (most recent call last)
in ()
11 plt.bar(index,data1,color=‘r’,label=‘a’)
12 plt.bar(index+a,data2,bottom=data1,color=‘b’,label=‘b’)
—> 13 plt.bar(index+2*a,data3,bottom=(data2+data1),color=‘g’,label=‘c’)
14 plt.legend(loc=2)
15 plt.show()

D:\anaconda\lib\site-packages\matplotlib\pyplot.py in bar(left, height, width, bottom, hold, data, **kwargs)
2702 try:
2703 ret = ax.bar(left, height, width=width, bottom=bottom, data=data,
-> 2704 **kwargs)
2705 finally:
2706 ax._hold = washold

D:\anaconda\lib\site-packages\matplotlib_init_.py in inner(ax, *args, **kwargs)
1896 warnings.warn(msg % (label_namer, func.name),
1897 RuntimeWarning, stacklevel=2)
-> 1898 return func(ax, *args, **kwargs)
1899 pre_doc = inner.doc
1900 if pre_doc is None:

D:\anaconda\lib\site-packages\matplotlib\axes_axes.py in bar(self, left, height, width, bottom, **kwargs)
2083 if len(bottom) != nbars:
2084 raise ValueError("incompatible sizes: argument ‘bottom’ "
-> 2085 “must be length %d or scalar” % nbars)
2086
2087 patches = []

ValueError: incompatible sizes: argument ‘bottom’ must be length 5 or scalar

plt.pie()

datas = [33,16,56,90,55]
colors = [‘red’,‘green’,‘blue’,‘pink’,‘yellow’]
labels = [‘xiaomi’,‘huawei’,‘apple’,‘oppo’,‘vivo’]
plt.pie(datas,colors=colors,labels=labels)
([<matplotlib.patches.Wedge at 0x15a210f2748>,
<matplotlib.patches.Wedge at 0x15a210fa3c8>,
<matplotlib.patches.Wedge at 0x15a21101048>,
<matplotlib.patches.Wedge at 0x15a21101c88>,
<matplotlib.patches.Wedge at 0x15a2110a908>],
[<matplotlib.text.Text at 0x15a210f2ef0>,
<matplotlib.text.Text at 0x15a210fab70>,
<matplotlib.text.Text at 0x15a211017f0>,
<matplotlib.text.Text at 0x15a2110a470>,
<matplotlib.text.Text at 0x15a211120f0>])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值