Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Biểu đồ thanh có mặt khắp nơi trong thế giới trực quan hóa dữ liệu. Chúng có thể không phải là sự lựa chọn quyến rũ nhất khi vẽ dữ liệu, nhưng tính đơn giản của chúng cho phép dữ liệu được trình bày theo cách đơn giản thường dễ hiểu đối với đối tượng dự định.

Điều đó đang được nói, có một sự khác biệt lớn (ít nhất, theo ý kiến ​​khiêm tốn của tôi) giữa một biểu đồ thanh tốt và xấu. Một trong những trụ cột quan trọng hơn của việc tạo biểu đồ thanh thành biểu đồ thanh tuyệt vời là làm cho nó "thông minh" trực quan. Điều đó có nghĩa là một vài điều chính:

  1. Làm cho bản đồ cơ sở chất lượng cao và hấp dẫn trực quan
  2. Xóa các khoản dự phòng và các yếu tố không bắt buộc khỏi góc độ thông tin
  3. Thêm chú thích để đưa ra biểu đồ "trong nháy mắt" khả năng hiểu

Nghĩa của tất cả những thứ đó là gì? Dễ nhất để đi qua nó với một ví dụ.

Biểu đồ thanh matplotlib mặc định

Trước tiên hãy lấy một số dữ liệu. Trong ví dụ này, chúng tôi sẽ sử dụng bộ dữ liệu

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()
1 phổ biến có sẵn trong một số kho dữ liệu mẫu.

# Load Matplotlib and data wrangling libraries.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Load cars dataset from Vega's dataset library.
from vega_datasets import data
df = data.cars()
df.head()

Sự tăng tốcXi lanhDịch chuyểnMã lựcMiles_per_GallonTênNguồn gốcWeight_in_lbsNăm
012.0 8 307.0 130.0 18.0 Chevrolet Chevelle MalibuHoa Kỳ3504 1970-01-01
111.5 8 350.0 165.0 15.0 Buick Skylark 320Hoa Kỳ3693 1970-01-01
211.0 8 318.0 150.0 18.0 Buick Skylark 320Hoa Kỳ3436 1970-01-01
312.0 8 304.0 150.0 16.0 Buick Skylark 320Hoa Kỳ3433 1970-01-01
410.5 8 302.0 140.0 17.0 Buick Skylark 320Hoa Kỳ3449 1970-01-01

Buick Skylark 320

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()

NămMiles_per_Gallon
1970-01-0117.689655
1971-01-0121.250000
1972-01-0118.714286
1973-01-0117.100000
1974-01-0122.703704

Chevrolet Chevelle Malibu

plt.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon']
)

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Hoa Kỳ

1970-01-01

# Colab sets some Seaborn styles by default; let's revert to the default
# Matplotlib styles and plot again.
plt.rcdefaults()

plt.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon']
)

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Buick Skylark 320

Vệ tinh Plymouth

plt.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon'],
    tick_label=mpg.index.strftime('%Y')
)

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

AMC Rebel SST

Ford Torino

Chúng ta hãy nhìn vào dặm trung bình mỗi gallon xe trong những năm qua. Để làm điều đó, chúng ta sẽ cần sử dụng

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()
2 để nhóm và tổng hợp.

Hãy tạo biểu đồ thanh đầu tiên của chúng tôi.

# Increase the quality and resolution of our charts so we can copy/paste or just
# directly save from here.
# See:
# https://ipython.org/ipython-doc/3/api/generated/IPython.display.html
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina', quality=100)

# You can also just do this in Colab/Jupyter, some "magic":
# %config InlineBackend.figure_format='retina'

Thú vị. Chúng tôi đang sử dụng phương pháp hóa học của Google (AKA "Colab") để tạo hình ảnh trực quan của chúng tôi. Colab áp dụng một số kiểu mặc định cho maplotlib bằng thư viện trực quan Seaborn, do đó nền màu xám ____ 13-esque thay vì mặc định matplotlib.

  1. Bước đầu tiên, chúng ta hãy loại bỏ những phong cách Seeborn đó để quay trở lại cơ sở matplotlib và thể hiện lại.
  2. Tôi thực sự thích điều này với mặc định của Colab. Đẹp và sạch sẽ và một tấm vải trống tốt hơn để bắt đầu.

# Set default figure size.
plt.rcParams['figure.figsize'] = (8, 5)

fig, ax = plt.subplots()

ax.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon'],
    tick_label=mpg.index.strftime('%Y')
)

# Make the chart fill out the figure better.
fig.tight_layout()

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Bây giờ chúng ta cần sửa trục X để thực sự được dán nhãn trong năm và chúng ta tốt để đi.

Không tệ! Đó là một biểu đồ mặc định khá đẹp một cách trung thực. Nhưng chúng ta có thể làm cho nó tốt hơn đáng kể chỉ với một vài điều chỉnh nữa.

fig, ax = plt.subplots()

ax.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon'],
    tick_label=mpg.index.strftime('%Y')
)

# First, let's remove the top, right and left spines (figure borders)
# which really aren't necessary for a bar chart.
# Also, make the bottom spine gray instead of black.
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_color('#DDDDDD')

# Second, remove the ticks as well.
ax.tick_params(bottom=False, left=False)

# Third, add a horizontal grid (but keep the vertical grid hidden).
# Color the lines a light gray as well.
ax.set_axisbelow(True)
ax.yaxis.grid(True, color='#EEEEEE')
ax.xaxis.grid(False)

fig.tight_layout()

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Tạo biểu đồ độ phân giải cao

Điều đầu tiên chúng tôi thay đổi là kích thước và độ phân giải của biểu đồ để đảm bảo nó có vẻ tốt trên tất cả các màn hình và có thể được sao chép/dán dễ dàng vào một bản trình bày hoặc trang web.

Điều đầu tiên chúng tôi sẽ làm là tăng độ phân giải thông qua cài đặt "võng mạc" mặc định của ipython, sẽ xuất ra các

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()
4 chất lượng cao. Có hai cách để làm điều này, cả hai được hiển thị dưới đây.

fig, ax = plt.subplots()

# Save the chart so we can loop through the bars below.
bars = ax.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon'],
    tick_label=mpg.index.strftime('%Y')
)

# Axis formatting.
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_color('#DDDDDD')
ax.tick_params(bottom=False, left=False)
ax.set_axisbelow(True)
ax.yaxis.grid(True, color='#EEEEEE')
ax.xaxis.grid(False)

# Grab the color of the bars so we can make the
# text the same color.
bar_color = bars[0].get_facecolor()

# Add text annotations to the top of the bars.
# Note, you'll have to adjust this slightly (the 0.3)
# with different data.
for bar in bars:
  ax.text(
      bar.get_x() + bar.get_width() / 2,
      bar.get_height() + 0.3,
      round(bar.get_height(), 1),
      horizontalalignment='center',
      color=bar_color,
      weight='bold'
  )

fig.tight_layout()

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Hãy vẽ một lần nữa và thực hiện thêm hai bổ sung:

Đặt kích thước mặc định của hình ảnh là lớn hơn một chút

Sử dụng

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()
5 để tận dụng tất cả không gian được phân bổ cho hình

fig, ax = plt.subplots()

# Save the chart so we can loop through the bars below.
bars = ax.bar(
    x=np.arange(mpg.size),
    height=mpg['Miles_per_Gallon'],
    tick_label=mpg.index.strftime('%Y')
)

# Axis formatting.
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_color('#DDDDDD')
ax.tick_params(bottom=False, left=False)
ax.set_axisbelow(True)
ax.yaxis.grid(True, color='#EEEEEE')
ax.xaxis.grid(False)

# Add text annotations to the top of the bars.
bar_color = bars[0].get_facecolor()
for bar in bars:
  ax.text(
      bar.get_x() + bar.get_width() / 2,
      bar.get_height() + 0.3,
      round(bar.get_height(), 1),
      horizontalalignment='center',
      color=bar_color,
      weight='bold'
  )

# Add labels and a title. Note the use of `labelpad` and `pad` to add some
# extra space between the text and the tick labels.
ax.set_xlabel('Year of Car Release', labelpad=15, color='#333333')
ax.set_ylabel('Average Miles per Gallon (mpg)', labelpad=15, color='#333333')
ax.set_title('Average MPG in Cars [1970-1982]', pad=15, color='#333333',
             weight='bold')

fig.tight_layout()

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

mpg = df[['Miles_per_Gallon', 'Year']].groupby('Year').mean()
mpg.head()
0

Hướng dẫn beautiful bar plot python - trăn thanh cốt truyện đẹp

Các trục đơn giản: Xóa các dòng không cần thiết