數據可視化基礎專題(十三):Matplotlib 基礎(五)常用圖表(三)環形圖、熱力圖、直方圖


環形圖

環形圖其實是另一種餅圖,使用的還是上面的 pie() 這個方法,這里只需要設置一下參數 wedgeprops 即可。

例子一:

import matplotlib.pyplot as plt

# 中文和負號的正常顯示
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 數據
edu = [0.2515,0.3724,0.3336,0.0368,0.0057]
labels = ['中專','大專','本科','碩士','其他']

# 讓本科學歷離圓心遠一點
explode = [0,0,0.1,0,0]

# 將橫、縱坐標軸標准化處理,保證餅圖是一個正圓,否則為橢圓
plt.axes(aspect='equal')

# 自定義顏色
colors=['#9999ff','#ff9999','#7777aa','#2442aa','#dd5555'] # 自定義顏色

# 繪制餅圖
plt.pie(x=edu,  # 繪圖數據
    explode = explode,  # 突出顯示大專人群
    labels = labels,  # 添加教育水平標簽
    colors = colors,  # 設置餅圖的自定義填充色
    autopct = '%.1f%%',  # 設置百分比的格式,這里保留一位小數
    wedgeprops = {'width': 0.3, 'edgecolor':'green'}
    )

# 添加圖標題
plt.title('xxx 公司員工教育水平分布')

# 保存圖形
plt.savefig('pie_demo1.png')

這個示例僅僅在前面示例的基礎上增加了一個參數 wedgeprops 的設置,我們看下結果:

 

 

熱力圖

plt.imshow(x, cmap)
import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(10, 10)
plt.imshow(x, cmap=plt.cm.hot)

# 顯示右邊顏色條
plt.colorbar()

plt.savefig('imshow_demo.png')

 

例子二

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
               origin='lower', extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())

plt.show()

 

 例子3

import matplotlib.pyplot as plt
import numpy as np


def func3(x, y):
    return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2 + y**2))


# make these smaller to increase the resolution
dx, dy = 0.05, 0.05

x = np.arange(-3.0, 3.0, dx)
y = np.arange(-3.0, 3.0, dy)
X, Y = np.meshgrid(x, y)

# when layering multiple images, the images need to have the same
# extent.  This does not mean they need to have the same shape, but
# they both need to render to the same coordinate system determined by
# xmin, xmax, ymin, ymax.  Note if you use different interpolations
# for the images their apparent extent could be different due to
# interpolation edge effects

extent = np.min(x), np.max(x), np.min(y), np.max(y)
fig = plt.figure(frameon=False)

Z1 = np.add.outer(range(8), range(8)) % 2  # chessboard
im1 = plt.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest',
                 extent=extent)

Z2 = func3(X, Y)

im2 = plt.imshow(Z2, cmap=plt.cm.viridis, alpha=.9, interpolation='bilinear',
                 extent=extent)

plt.show()

 

直方圖

例子1

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter

# Fixing random state for reproducibility
np.random.seed(19680801)
N_points = 100000
n_bins = 20

# Generate a normal distribution, center at x=0 and y=5
x = np.random.randn(N_points)
y = .4 * x + np.random.randn(100000) + 5

fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)

# We can set the number of bins with the `bins` kwarg
axs[0].hist(x, bins=n_bins)
axs[1].hist(y, bins=n_bins)

 

 例子2

fig, axs = plt.subplots(1, 2, tight_layout=True)

# N is the count in each bin, bins is the lower-limit of the bin
N, bins, patches = axs[0].hist(x, bins=n_bins)

# We'll color code by height, but you could use any scalar
fracs = N / N.max()

# we need to normalize the data to 0..1 for the full range of the colormap
norm = colors.Normalize(fracs.min(), fracs.max())

# Now, we'll loop through our objects and set the color of each accordingly
for thisfrac, thispatch in zip(fracs, patches):
    color = plt.cm.viridis(norm(thisfrac))
    thispatch.set_facecolor(color)

# We can also normalize our inputs by the total number of counts
axs[1].hist(x, bins=n_bins, density=True)

# Now we format the y-axis to display percentage
axs[1].yaxis.set_major_formatter(PercentFormatter(xmax=1))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM