python中利用matplotlib画图
生活随笔
收集整理的這篇文章主要介紹了
python中利用matplotlib画图
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
介紹三種比較簡單的方法
- 基于matplotlib的畫圖方式
plt.plot(),常用款
plt.hist(), 畫直方圖
plt.pie(),畫餅狀圖
plt.figure() - 基于pandas的畫圖
s.plot() s是pandas的Series對象
df.plot() df是pandas的DataFrame對象
1.1. plt.plot()#繪制y關(guān)于x的變化關(guān)系.
x,y是成對出現(xiàn)的。可以省略x,則y是關(guān)于y的個數(shù)的函數(shù)關(guān)系。
當(dāng)y是Series或DataFrame對象對象時,不出現(xiàn)x
[fmt]]可以設(shè)置線性,顏色,樣式等。
Plot y versus x as lines and/or markers
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)
以一個比較簡單的例子入手:
import numpy as np from matplotlib import pyplot as plt %matplotlib inlinex = np.arange(-10,11) y = x**2 plt.plot(x,y)- 增加一些功能
設(shè)置標(biāo)題、坐標(biāo)軸標(biāo)簽、軸邊界、軸刻度、顯示中文及正負號
- 增加圖例
配合plot()中的label參數(shù),設(shè)置圖例。loc設(shè)置圖例的位置。color設(shè)置顏色,linestyle設(shè)置顏色,marker設(shè)置有值處點的形狀。
- plt.plot()的參數(shù)是Series對象
- plt.plot()的參數(shù)是DataFrame對象。DataFrame對象畫圖時,使用df.plot()更好,圖例顯示的就是列名。
1.2 plt.hist()畫直方圖
1.3. plt.pie()畫餅狀圖
2.1 s.plot()
2.2 df.plot()
通過df.plot(kind='line')畫圖,其中的kind參數(shù)可取‘line’,‘bar’,‘kde’(密度圖),‘hist’,‘a(chǎn)rea’(面積圖)等。返回對象axes
- 保存圖像plt.savefig('a.png')
3.1 子圖創(chuàng)建1 - 先建立子圖然后填充圖表
在子圖中添加標(biāo)題
ax1.title.set_text('First Plot')
3.2 創(chuàng)建一個新的figure,并返回一個subplot對象的numpy數(shù)組 → plt.subplot
# 子圖創(chuàng)建2 - 創(chuàng)建一個新的figure,并返回一個subplot對象的numpy數(shù)組 → plt.subplotfig,axes = plt.subplots(2,3,figsize=(10,4)) ts = pd.Series(np.random.randn(1000).cumsum()) ts2 = pd.Series(np.random.randint(100,size=100)) print(axes, axes.shape, type(axes)) # 生成圖表對象的數(shù)組ax1 = axes[0,1] ax1.plot(ts) ax2 = axes[0,2] ax2.plot(ts2)
參數(shù)調(diào)整
colorbar配合inshow使用
import numpy as np from matplotlib import pyplot as plt m = np.linspace(-100,100,50) n = np.linspace(-100,100,50) x,y = np.meshgrid(m,n) z = x**2 + y**2plt.imshow(z,cmap='spring') plt.colorbar(shrink=0.8)# 顏色條占圖高的比例 plt.show()總結(jié)
以上是生活随笔為你收集整理的python中利用matplotlib画图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。