Tổng quan
Giảng dạy: 15 phút Bài tập: 15 phút 15 min
Exercises: 15 minCâu hỏi
Làm cách nào để vẽ dữ liệu của mình?
Làm thế nào tôi có thể lưu cốt truyện của tôi để xuất bản?
Mục tiêu
Tạo một biểu đồ chuỗi thời gian hiển thị một tập dữ liệu duy nhất.
Tạo một biểu đồ phân tán hiển thị mối quan hệ giữa hai bộ dữ liệu.
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot[time, position]
plt.xlabel['Time [hr]']
plt.ylabel['Position [km]']
7 là thư viện âm mưu khoa học được sử dụng rộng rãi nhất trong Python.
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot[time, position]
plt.xlabel['Time [hr]']
plt.ylabel['Position [km]']
- Thường sử dụng một thư viện phụ được gọi là
8.time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
- Notebook Jupyter sẽ hiển thị các sơ đồ nội tuyến theo mặc định.
import matplotlib.pyplot as plt
- Sơ đồ đơn giản sau đó [công bằng] đơn giản để tạo.
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot[time, position]
plt.xlabel['Time [hr]']
plt.ylabel['Position [km]']
Hiển thị tất cả các số liệu mở
Trong ví dụ Jupyter Notebook, chạy ô nên tạo hình ngay bên dưới mã. Hình cũng được bao gồm trong tài liệu Notebook để xem trong tương lai. Tuy nhiên, các môi trường Python khác như phiên Python tương tác bắt đầu từ một thiết bị đầu cuối hoặc tập lệnh Python được thực thi thông qua dòng lệnh yêu cầu một lệnh bổ sung để hiển thị hình.
Hướng dẫn
7 hiển thị một con số:time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Lệnh này cũng có thể được sử dụng trong một cuốn sổ - ví dụ, để hiển thị nhiều hình nếu một số được tạo bởi một ô.
Vẽ dữ liệu trực tiếp từ import pandas as pd
data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country']
# Extract year from last 4 characters of each column name
# The current column names are structured as 'gdpPercap_[year]',
# so we want to keep the [year] part only for clarity when plotting GDP vs. years
# To do this we use strip[], which removes from the string the characters stated in the argument
# This method works on strings, so we call str before strip[]
years = data.columns.str.strip['gdpPercap_']
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype[int]
data.loc['Australia'].plot[]
0.
import pandas as pd
data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country']
# Extract year from last 4 characters of each column name
# The current column names are structured as 'gdpPercap_[year]',
# so we want to keep the [year] part only for clarity when plotting GDP vs. years
# To do this we use strip[], which removes from the string the characters stated in the argument
# This method works on strings, so we call str before strip[]
years = data.columns.str.strip['gdpPercap_']
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype[int]
data.loc['Australia'].plot[]
- Chúng ta cũng có thể vẽ các khung dữ liệu gấu trúc.
- Điều này ngầm sử dụng
8.time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
- Trước khi vẽ, chúng tôi chuyển đổi các tiêu đề cột từ kiểu dữ liệu
2 sangimport pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
3, vì chúng biểu thị các giá trị sốimport pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
import pandas as pd
data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country']
# Extract year from last 4 characters of each column name
# The current column names are structured as 'gdpPercap_[year]',
# so we want to keep the [year] part only for clarity when plotting GDP vs. years
# To do this we use strip[], which removes from the string the characters stated in the argument
# This method works on strings, so we call str before strip[]
years = data.columns.str.strip['gdpPercap_']
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype[int]
data.loc['Australia'].plot[]
Chọn và chuyển đổi dữ liệu, sau đó vẽ nó.
- Theo mặc định,
4 sơ đồ với các hàng là trục X.import pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
- Chúng ta có thể chuyển đổi dữ liệu để vẽ nhiều chuỗi.
data.T.plot[]
plt.ylabel['GDP per capita']
Nhiều phong cách của cốt truyện có sẵn.
- Ví dụ, thực hiện một cốt truyện bằng cách sử dụng một phong cách fancier.
plt.style.use['ggplot']
data.T.plot[kind='bar']
plt.ylabel['GDP per capita']
Dữ liệu cũng có thể được vẽ trực tiếp bằng cách gọi hàm time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot[time, position]
plt.xlabel['Time [hr]']
plt.ylabel['Position [km]']
7 import pandas as pd
data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country']
# Extract year from last 4 characters of each column name
# The current column names are structured as 'gdpPercap_[year]',
# so we want to keep the [year] part only for clarity when plotting GDP vs. years
# To do this we use strip[], which removes from the string the characters stated in the argument
# This method works on strings, so we call str before strip[]
years = data.columns.str.strip['gdpPercap_']
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype[int]
data.loc['Australia'].plot[]
6.
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot[time, position]
plt.xlabel['Time [hr]']
plt.ylabel['Position [km]']
import pandas as pd
data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country']
# Extract year from last 4 characters of each column name
# The current column names are structured as 'gdpPercap_[year]',
# so we want to keep the [year] part only for clarity when plotting GDP vs. years
# To do this we use strip[], which removes from the string the characters stated in the argument
# This method works on strings, so we call str before strip[]
years = data.columns.str.strip['gdpPercap_']
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype[int]
data.loc['Australia'].plot[]
- Lệnh là
7import pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
- Màu sắc và định dạng của các điểm đánh dấu cũng có thể được chỉ định là một đối số tùy chọn bổ sung, ví dụ:
8 là một đường màu xanh lam,import pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
9 là một đường nét đứt màu xanh lá cây.import pandas as pd data = pd.read_csv['data/gapminder_gdp_oceania.csv', index_col='country'] # Extract year from last 4 characters of each column name # The current column names are structured as 'gdpPercap_[year]', # so we want to keep the [year] part only for clarity when plotting GDP vs. years # To do this we use strip[], which removes from the string the characters stated in the argument # This method works on strings, so we call str before strip[] years = data.columns.str.strip['gdpPercap_'] # Convert year values to integers, saving results back to dataframe data.columns = years.astype[int] data.loc['Australia'].plot[]
Nhận dữ liệu Úc từ DataFrame
years = data.columns
gdp_australia = data.loc['Australia']
plt.plot[years, gdp_australia, 'g--']
Có thể vẽ nhiều bộ dữ liệu với nhau.
# Select two countries' worth of data.
gdp_australia = data.loc['Australia']
gdp_nz = data.loc['New Zealand']
# Plot with differently-colored markers.
plt.plot[years, gdp_australia, 'b-', label='Australia']
plt.plot[years, gdp_nz, 'g-', label='New Zealand']
# Create legend.
plt.legend[loc='upper left']
plt.xlabel['Year']
plt.ylabel['GDP per capita [$]']
Thêm một huyền thoại
Thông thường khi vẽ nhiều bộ dữ liệu trên cùng một hình, mong muốn có một huyền thoại mô tả dữ liệu.
Điều này có thể được thực hiện trong
7 trong hai giai đoạn:time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
- Cung cấp nhãn cho mỗi bộ dữ liệu trong hình:
plt.plot[years, gdp_australia, label='Australia'] plt.plot[years, gdp_nz, label='New Zealand']
- Hướng dẫn
7 để tạo ra truyền thuyết.time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Theo mặc định matplotlib sẽ cố gắng đặt truyền thuyết ở vị trí phù hợp. Nếu bạn thà chỉ định một vị trí, điều này có thể được thực hiện với đối số
2, ví dụ: để đặt huyền thoại ở góc trên bên trái của cốt truyện, chỉ địnhdata.T.plot[] plt.ylabel['GDP per capita']
3data.T.plot[] plt.ylabel['GDP per capita']
- Vẽ một âm mưu phân tán tương quan GDP của Úc và New Zealand
- Sử dụng
4 hoặcdata.T.plot[] plt.ylabel['GDP per capita']
5data.T.plot[] plt.ylabel['GDP per capita']
plt.scatter[gdp_australia, gdp_nz]
data.T.plot.scatter[x = 'Australia', y = 'New Zealand']
Timea và cực đại
Điền vào các chỗ trống bên dưới để vẽ GDP tối thiểu bình quân đầu người theo thời gian cho tất cả các quốc gia ở châu Âu. Sửa đổi nó một lần nữa để vẽ GDP tối đa bình quân đầu người theo thời gian cho châu Âu.
0time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Dung dịch
1time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Mối tương quan
Sửa đổi ví dụ trong các ghi chú để tạo ra một biểu đồ phân tán cho thấy mối quan hệ giữa GDP tối thiểu và tối đa trên đầu người giữa các quốc gia ở châu Á cho mỗi năm trong bộ dữ liệu. Bạn thấy mối quan hệ nào [nếu có]?
Dung dịch
2time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Mối tương quan
Sửa đổi ví dụ trong các ghi chú để tạo ra một biểu đồ phân tán cho thấy mối quan hệ giữa GDP tối thiểu và tối đa trên đầu người giữa các quốc gia ở châu Á cho mỗi năm trong bộ dữ liệu. Bạn thấy mối quan hệ nào [nếu có]?
3time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Dung dịch
Mối tương quan
Sửa đổi ví dụ trong các ghi chú để tạo ra một biểu đồ phân tán cho thấy mối quan hệ giữa GDP tối thiểu và tối đa trên đầu người giữa các quốc gia ở châu Á cho mỗi năm trong bộ dữ liệu. Bạn thấy mối quan hệ nào [nếu có]?
Không có mối tương quan cụ thể nào có thể được nhìn thấy giữa các giá trị GDP tối thiểu và tối đa hàng năm. Có vẻ như vận may của các nước châu Á không vươn lên và cùng nhau.
4time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Bạn có thể lưu ý rằng sự thay đổi tối đa cao hơn nhiều so với mức tối thiểu. Hãy xem tối đa và các chỉ mục tối đa:
Dung dịch
Mối tương quan
Sửa đổi ví dụ trong các ghi chú để tạo ra một biểu đồ phân tán cho thấy mối quan hệ giữa GDP tối thiểu và tối đa trên đầu người giữa các quốc gia ở châu Á cho mỗi năm trong bộ dữ liệu. Bạn thấy mối quan hệ nào [nếu có]?
Không có mối tương quan cụ thể nào có thể được nhìn thấy giữa các giá trị GDP tối thiểu và tối đa hàng năm. Có vẻ như vận may của các nước châu Á không vươn lên và cùng nhau.
Bạn có thể lưu ý rằng sự thay đổi tối đa cao hơn nhiều so với mức tối thiểu. Hãy xem tối đa và các chỉ mục tối đa:
Có vẻ như sự thay đổi trong giá trị này là do sự sụt giảm mạnh sau năm 1972. Một số địa chính trị có lẽ? Với sự thống trị của các nước sản xuất dầu, có lẽ chỉ số thô Brent sẽ tạo ra một so sánh thú vị? Trong khi Myanmar liên tục có GDP thấp nhất, thì GDB quốc gia cao nhất đã thay đổi đáng chú ý hơn.
Nhiều mối tương quan hơn
5time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Sẽ lưu hình hiện tại vào tệp
7. Định dạng tệp sẽ tự động được suy ra từ tiện ích mở rộng tên tệp [các định dạng khác là PDF, PS, EPS và SVG].data.T.plot[] plt.ylabel['GDP per capita']
Lưu ý rằng các chức năng trong
8 đề cập đến một biến số toàn cầu và sau khi một hình đã được hiển thị lên màn hình [ví dụ: vớidata.T.plot[] plt.ylabel['GDP per capita']
9] matplotlib sẽ làm cho biến này tham khảo một hình trống mới. Do đó, hãy đảm bảo bạn gọidata.T.plot[] plt.ylabel['GDP per capita']
0 trước khi biểu đồ được hiển thị lên màn hình, nếu không bạn có thể tìm thấy một tệp có âm mưu trống.plt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
Khi sử dụng DataFrames, dữ liệu thường được tạo và vẽ để sàng lọc theo một dòng và
0 dường như không phải là một cách tiếp cận có thể. Sau đó, một khả năng lưu con số vào tệp làplt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
- Lưu tham chiếu đến hình hiện tại trong một biến cục bộ [với
2]plt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
- Gọi phương thức lớp
3 từ biến đó.plt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
6time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Làm cho âm mưu của bạn có thể truy cập được
Bất cứ khi nào bạn tạo ra các lô để đi vào một tờ giấy hoặc một bài thuyết trình, có một vài điều bạn có thể làm để đảm bảo rằng mọi người có thể hiểu cốt truyện của bạn.
- Luôn đảm bảo văn bản của bạn đủ lớn để đọc. Sử dụng tham số
4 trongplt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
5,plt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
6,plt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
7 vàplt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
8 vàplt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
9 vớiplt.style.use['ggplot'] data.T.plot[kind='bar'] plt.ylabel['GDP per capita']
0 để tăng kích thước văn bản của các số trên các trục của bạn.years = data.columns gdp_australia = data.loc['Australia'] plt.plot[years, gdp_australia, 'g--']
- Tương tự, bạn nên làm cho các yếu tố biểu đồ của bạn dễ dàng nhìn thấy. Sử dụng
1 để tăng kích thước của các điểm đánh dấu phân tán của bạn vàyears = data.columns gdp_australia = data.loc['Australia'] plt.plot[years, gdp_australia, 'g--']
2 để tăng kích thước của các dòng cốt truyện của bạn.years = data.columns gdp_australia = data.loc['Australia'] plt.plot[years, gdp_australia, 'g--']
- Sử dụng màu sắc [và không có gì khác] để phân biệt giữa các yếu tố cốt truyện khác nhau sẽ làm cho các lô của bạn không thể đọc được với bất kỳ ai là mù màu, hoặc những người tình cờ có máy in văn phòng đen trắng. Đối với các dòng, tham số
3 cho phép bạn sử dụng các loại dòng khác nhau. Đối với các biểu đồ phân tán,years = data.columns gdp_australia = data.loc['Australia'] plt.plot[years, gdp_australia, 'g--']
4 cho phép bạn thay đổi hình dạng điểm của mình. Nếu bạn không chắc chắn về màu sắc của mình, bạn có thể sử dụng Coblis hoặc Color Oracle để mô phỏng các lô của bạn sẽ trông như thế nào đối với những người bị mù màu.years = data.columns gdp_australia = data.loc['Australia'] plt.plot[years, gdp_australia, 'g--']
Những điểm chính
7 là thư viện âm mưu khoa học được sử dụng rộng rãi nhất trong Python.time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot[time, position] plt.xlabel['Time [hr]'] plt.ylabel['Position [km]']
Vẽ dữ liệu trực tiếp từ một DataFrame của Pandas.
Chọn và chuyển đổi dữ liệu, sau đó vẽ nó.
Nhiều kiểu cốt truyện có sẵn: Xem bộ sưu tập đồ thị Python để biết thêm các tùy chọn.
Có thể vẽ nhiều bộ dữ liệu với nhau.