利用python進行數據分析matplotlib_api入門

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 09:27:37 2019

@author: weiping
"""

import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd
plt.plot(np.arange(10))
plt.show()

fig,axes = plt.subplots(2,2,sharex = True,sharey = True) # sharex/y 使所有的subplot使用相同的軸刻度
for i in range(2):
    for j in range(2):
        axes[i,j].plot(np.random.rand(500),color = '#CECECE',alpha = 1)
plt.subplots_adjust(wspace = 0.1,hspace = 0.1) # h/wspace設置高度和寬度的百分比[0-1] 

plt.plot(np.random.randn(30).cumsum(),'ko--')
plt.show()

'''
pandas中繪圖
'''
df = pd.DataFrame(np.random.randn(10,4).cumsum(0),
                  columns = ['a','b','c','d'])
df.plot()
df.plot(kind = 'hist',alpha = .3) #kind 可以是 line  bar  barh kde hist 等

df = pd.DataFrame(np.random.randn(10000),
                  columns = ['a'])
df.hist(bins = 100)


-----

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
x = range(2000,2010,1)
y = range(1900,1920,2)
plt.plot(y,x,color = 'red',linestyle = '-.',linewidth = 5.0)
plt.show()

x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017']
y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000]
y_data2 = [52000, 54200, 51500,58300, 56800, 59500, 62700]
plt.plot(x_data,y_data,color = 'red',linewidth = 2,linestyle = '-.',label = 'java基礎')
plt.plot(x_data,y_data2,color = 'blue',linewidth = 5,linestyle = ':' ,label = 'python基礎')
my_font = fm.FontProperties(fname = r'C:\Windows\Fonts\simsun.ttc')
plt.legend(loc = 'best',prop = my_font)

plt.xlabel('year')
plt.ylabel('count')

plt.title('tushu')

plt.yticks([50000,70000,100000],[r'一般',r'優秀',r'火爆'])

plt.show()

plt.plot(x_data,y_data,'dr')
plt.show()

x = [1,3,5,2,4] 
y = [2,4,5,1,3] 
plt.plot(x, y) #將x,y軸座標數據傳入,第三個參數是展現形式,默認是折線圖 
plt.plot(x, y, 'ok-.') #黑色散點圖
plt.xlim(0,10) #設置x範圍在0到10 
plt.ylim(0,10) #設置y範圍在0到10 
plt.title("show") #設置標題名,在中上方 
plt.xlabel("num") #設置x軸名稱,在中下方 
plt.ylabel("age") #設置y軸名稱,在中左方 
plt.show() #可視化顯示數據,注意show了之後畫布就被清空了,前面的內容下次就show不出來
 


fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis')
plt.show()


fig,ax = plt.subplots(nrows = 4 ,ncols = 4 )
ax[0,0].set(title = 'Upper Left')
ax[0,2].set(title = 'Upper Right')
ax[2,0].set(title = 'Lower Left')
ax[2,2].set(title = 'Lower Right')
plt.show()


fig = plt.figure()
ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(322)
ax3 = fig.add_subplot(423)
ax4 = fig.add_subplot(424)
plt.show()
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(322)
ax3 = fig.add_subplot(423)
ax4 = fig.add_subplot(424)
x = np.linspace(0,np.pi)
y_s = np.sin(x)
y_t = np.tan(x)
ax1.plot(x,y_t)
ax2.plot(x,y_s,color = 'red',marker = 'd',linestyle = '-.')
plt.show()

'''
散點圖/氣泡圖
'''
x = range(10)
y = np.random.randn(10)
plt.scatter(x,y)
plt.show()
#---------------
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
area = (30*np.random.rand(50)) **2
plt.scatter(x,y,s = area,c=colors,alpha = .6)
plt.show()
'''
條形圖
'''

np.random.seed(1)
x = np.arange(5)
y = np.random.randn(5)

fig,ax = plt.subplots(ncols =2,figsize = plt.figaspect(1./2))

ver_bar = ax[0].bar(x,y)   #水平
hor_bar = ax[1].barh(x,y) #垂直

ax[0].axhline()
ax[1].axvline() #垂直
plt.show()

#不同顏色

fig,ax = plt.subplots()

bars = ax.bar(x,y)
for bar,h in zip(bars,y):
    if h <= 0 :
        bar.set(color = 'red')
plt.show()

'''
直方圖
'''

np.random.seed(1991919191)
n_bins = 10
x = np.random.randn(1000,3)
fig,axes = plt.subplots(nrows = 2,ncols = 2 )
ax1,ax2,ax3,ax4 = axes.flatten()
colors = ['red','blue','black']
ax1.hist(x,n_bins,density = True,histtype = 'bar',color = colors,label = colors)

ax2.hist(x,n_bins,density = True,histtype = 'barstacked')
ax3.hist(x,n_bins,histtype = 'barstacked',rwidth = 0.5)
ax4.hist(x[:,0])
plt.show()


''''
餅圖
''''

colors = ['red','blue','black']
sizes  = [ 12,14,18]
explode=(0,0.2,0)
fig,(ax1,ax2) = plt.subplots(2)
ax1.pie(sizes,labels = colors)
ax2.pie(sizes,autopct = '%1.2f%%',shadow = True,startangle=90,explode = explode,pctdistance = 1.12)
ax2.axis('equal')
ax2.legend(labels = colors,loc = 'best')
plt.show()

'''
箱型圖
'''
np.random.seed(1991919191)

x = np.random.randn(1000,3)
fig,(ax1,ax2) = plt.subplots(2)
ax1.boxplot(x[:,0])
ax2.boxplot(x,vert = False)
plt.show()

可以參考https://www.cnblogs.com/zhizhan/p/5615947.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章