Phần 22: Violin Plot – Matplotib Basic

Phần 22: Violin Plot                        – Matplotib Basic

1. Khái niệm

Biểu đồ violin giống nhau như biểu đồ nến, ngoại trừ việc chúng hiển thị mật độ xác suất của dữ liệu ở những giá trị khác nhau. Các biểu đồ này gồm 1 điểm đánh dấu cho trung vị của dữ liệu và 1 nến hiển thị phạm vi liên phần tư, như ở trong các plot field tiêu chuẩn. Phủ trên plot field này là ước lượng mật độ nhân. Giống như field plot, plot violin được dùng để thể hiện sự so sánh của 1 phân phối thay đổi (hay phân phối mẫu) trên những “danh mục” khác nhau.
1 plot violin có nhiều thông tin hơn 1 plot field đơn thuần. Trên thực tế, trong khi biểu đồ nến chỉ hiển thị thống kê tóm tắt như phạm vi trung bình / trung vị và giữa những phần, thì biểu đồ violin hiển thị tất cả phân phối dữ liệu.
import matplotlib.pyplot as plt

np.random.seed(10)
collectn_1 = np.random.regular(100, 10, 200)
collectn_2 = np.random.regular(80, 30, 200)
collectn_3 = np.random.regular(90, 20, 200)
collectn_4 = np.random.regular(70, 25, 200)

## mix these totally different collections into an inventory
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a determine occasion
fig = plt.determine()

# Create an axes occasion
ax = fig.add_axes([0,0,1,1])

# Create the boxplot
bp = ax.violinplot(data_to_plot)
plt.present()

2. Ví dụ :

Ví dụ 1 : so sánh giữa biểu đồ violin và biểu đồ nến :
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(9, 4))

# Fixing random state for reproducibility
np.random.seed(19680801)


# generate some random take a look at information
all_data = [np.random.normal(0, std, 100) for std in range(6, 10)]

# plot violin plot
axes[0].violinplot(all_data,
                   showmeans=False,
                   showmedians=True)
axes[0].set_title('Violin plot')

# plot field plot
axes[1].boxplot(all_data)
axes[1].set_title('Box plot')

# including horizontal grid strains
for ax in axes:
    ax.yaxis.grid(True)
    ax.set_xticks([y + 1 for y in range(len(all_data))])
    ax.set_xlabel('Four separate samples')
    ax.set_ylabel('Observed values')

# add x-tick labels
plt.setp(axes, xticks=[y + 1 for y in range(len(all_data))],
         xticklabels=['x1', 'x2', 'x3', 'x4'])
plt.present()
Ví dụ 2 :
import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)


# pretend information
fs = 10  # fontsize
pos = [1, 2, 4, 5, 7, 8]
information = [np.random.normal(0, std, size=100) for std in pos]

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6))

axes[0, 0].violinplot(information, pos, factors=20, widths=0.3,
                      showmeans=True, showextrema=True, showmedians=True)
axes[0, 0].set_title('Custom violinplot 1', fontsize=fs)

axes[0, 1].violinplot(information, pos, factors=40, widths=0.5,
                      showmeans=True, showextrema=True, showmedians=True,
                      bw_method='silverman')
axes[0, 1].set_title('Custom violinplot 2', fontsize=fs)

axes[0, 2].violinplot(information, pos, factors=60, widths=0.7, showmeans=True,
                      showextrema=True, showmedians=True, bw_method=0.5)
axes[0, 2].set_title('Custom violinplot 3', fontsize=fs)

axes[1, 0].violinplot(information, pos, factors=80, vert=False, widths=0.7,
                      showmeans=True, showextrema=True, showmedians=True)
axes[1, 0].set_title('Custom violinplot 4', fontsize=fs)

axes[1, 1].violinplot(information, pos, factors=100, vert=False, widths=0.9,
                      showmeans=True, showextrema=True, showmedians=True,
                      bw_method='silverman')
axes[1, 1].set_title('Custom violinplot 5', fontsize=fs)

axes[1, 2].violinplot(information, pos, factors=200, vert=False, widths=1.1,
                      showmeans=True, showextrema=True, showmedians=True,
                      bw_method=0.5)
axes[1, 2].set_title('Custom violinplot 6', fontsize=fs)

for ax in axes.flat:
    ax.set_yticklabels([])

fig.suptitle("Violin Plotting Examples")
fig.subplots_adjust(hspace=0.4)
plt.present()
Ví dụ 3 : Điều chỉnh biểu đồ violin
Ví dụ này trình bày cách tùy chỉnh hoàn toàn các plot violin. Biểu đồ đầu tiên hiển thị kiểu mặc định bằng việc chỉ cung cấp dữ liệu. Biểu đồ thứ 2 đầu tiên giới hạn những gì matplotlib vẽ với những kwargs bổ sung thêm. Sau đó, 1 biểu diễn đơn giản của 1 biểu đồ nến được vẽ trên đầu trang
import matplotlib.pyplot as plt
import numpy as np


def adjacent_values(vals, q1, q3):
    upper_adjacent_value = q3 + (q3 - q1) * 1.5
    upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])

    lower_adjacent_value = q1 - (q3 - q1) * 1.5
    lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
    return lower_adjacent_value, upper_adjacent_value


def set_axis_style(ax, labels):
    ax.get_xaxis().set_tick_params(route='out')
    ax.xaxis.set_ticks_position('backside')
    ax.set_xticks(np.arange(1, len(labels) + 1))
    ax.set_xticklabels(labels)
    ax.set_xlim(0.25, len(labels) + 0.75)
    ax.set_xlabel('Sample identify')


# create take a look at information
np.random.seed(19680801)
information = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 4), sharey=True)

ax1.set_title('Default violin plot')
ax1.set_ylabel('Observed values')
ax1.violinplot(information)

ax2.set_title('Customized violin plot')
components = ax2.violinplot(
        information, showmeans=False, showmedians=False,
        showextrema=False)

for computer in components['bodies']:
    computer.set_facecolor('#D43F3A')
    computer.set_edgecolor('black')
    computer.set_alpha(1)

quartile1, medians, quartile3 = np.percentile(information, [25, 50, 75], axis=1)
whiskers = np.array([
    adjacent_values(sorted_array, q1, q3)
    for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])
whiskersMin, whiskersMax = whiskers[:, 0], whiskers[:, 1]

inds = np.arange(1, len(medians) + 1)
ax2.scatter(inds, medians, marker='o', coloration='white', s=30, zorder=3)
ax2.vlines(inds, quartile1, quartile3, coloration='ok', linestyle='-', lw=5)
ax2.vlines(inds, whiskersMin, whiskersMax, coloration='ok', linestyle='-', lw=1)

# set fashion for the axes
labels = ['A', 'B', 'C', 'D']
for ax in [ax1, ax2]:
    set_axis_style(ax, labels)

plt.subplots_adjust(backside=0.15, wspace=0.05)
plt.present()

admin

Leave a Reply

Your email address will not be published. Required fields are marked *