八、面積圖、填圖、餅圖

 

 

In [ ]:
'''
面積圖、填圖、餅圖

plt.plot.area()
plt.fill(), plt.fill_between()
plt.pie()

'''
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
In [4]:
# 面積圖

fig,axes = plt.subplots(2,1,figsize = (8,6))
df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])

df1.plot.area(colormap = 'Greens_r',alpha = 0.5,ax = axes[0])   # 默認堆疊(必須都是正值)
df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])
# 使用Series.plot.area()和DataFrame.plot.area()建立面積圖
# stacked:是否堆疊,默認狀況下,區域圖被堆疊
# 爲了產生堆積面積圖,每列必須是正值或所有負值!
# 當數據有NaN時候,自動填充0,因此圖標籤須要清洗掉缺失值
Out[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x22a4ad2ba58>
 
In [11]:
# 填圖

fig,axes = plt.subplots(2,1,figsize = (8,6))

x = np.linspace(0, 1, 500)
y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)
y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)

axes[0].fill(x, y1, 'r',alpha=0.5,label='y1')
axes[0].fill(x, y2, 'g',alpha=0.5,label='y2')

# 對函數與座標軸之間的區域進行填充,使用fill函數
# 也可寫成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)

x = np.linspace(0, 5 * np.pi, 1000) 
y1 = np.sin(x)  
y2 = np.sin(2 * x)  
axes[1].fill_between(x, y1, 0.5, color ='b',alpha=0.5,label='area')  
# # 填充兩個函數之間的區域,使用fill_between函數

for i in range(2):
    axes[i].legend()
    axes[i].grid()
# 添加圖例、格網
 
In [24]:
# 餅圖 plt.pie()
# plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, 
# radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)

s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
plt.axis('equal')  # 保證長寬相等


import matplotlib.pyplot as plt  
font = { 
        'color'  : 'darkred',  
        'weight' : 'normal',  
        'size'   : 16,  
        }  

plt.pie(s,
       explode = [0.1,0,0,0],
       labels = s.index,
       colors=['r', 'g', 'b', 'c'],
       autopct='%.2f%%',
       pctdistance=0.6,
       labeldistance = 1.2,
       shadow = True,
       startangle=0,
       radius=1.5,
       frame=False,
       textprops = { 'fontsize': 20, 'color': 'k'},
       )
?plt.pie
print(s)
# 第一個參數:數據
# explode:指定每部分的偏移量
# labels:標籤
# colors:顏色
# autopct:餅圖上的數據標籤顯示方式
# pctdistance:每一個餅切片的中心和經過autopct生成的文本開始之間的比例
# labeldistance:被畫餅標記的直徑,默認值:1.1
# shadow:陰影
# startangle:開始角度
# radius:半徑
# frame:圖框
# counterclock:指定指針方向,順時針或者逆時針
# textprops  設置餅圖中文本的屬性,如字體大小、顏色等;
 
a    2.603817
b    0.471257
c    0.075976
d    0.163699
Name: series, dtype: float64
 
In [ ]:
 
In [ ]:
相關文章
相關標籤/搜索