Dalam contoh Notebook Jupyter kami, menjalankan sel harus menghasilkan angka langsung di bawah kode. Angka tersebut juga disertakan dalam dokumen Notebook untuk dilihat di masa mendatang. Namun, lingkungan Python lain seperti sesi Python interaktif yang dimulai dari terminal atau skrip Python yang dijalankan melalui baris perintah memerlukan perintah tambahan untuk menampilkan gambar.
Instruksikan time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _9 untuk menunjukkan angka
plt.show() _
Perintah ini juga dapat digunakan di dalam Notebook - misalnya, untuk menampilkan banyak gambar jika beberapa dibuat oleh satu sel
Plot data langsung dari plt.show() _2
- Kami juga dapat memplot bingkai data Panda
- Ini secara implisit menggunakan
- Sebelum memplot, kami mengonversi judul kolom dari tipe data plt.show() 4 menjadi plt.show() 5, karena mewakili nilai numerik, menggunakan str. replace() untuk menghapus awalan plt.show() _6 dan kemudian astype(int) untuk mengubah rangkaian nilai string (plt.show() 7) menjadi serangkaian bilangan bulat. plt.show() _8
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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() _
Pilih dan ubah data, lalu plot
- Secara default, plot dengan baris sebagai sumbu X
- Kami dapat mengubah urutan data untuk memplot beberapa seri
data.T.plot() plt.ylabel('GDP per capita') _
Banyak gaya plot yang tersedia
- Misalnya, lakukan plot batang menggunakan gaya yang lebih menarik
plt.style.use('ggplot') data.T.plot(kind='bar') plt.ylabel('GDP per capita')
Data juga dapat diplot dengan memanggil fungsi time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') 9 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 1 secara langsung
- Perintahnya adalah 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 2
- Warna dan format penanda juga dapat ditentukan sebagai argumen opsional tambahan e. g. , 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() _3 adalah garis biru, 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 4 adalah garis putus-putus hijau
Dapatkan data Australia dari kerangka data
years = data.columns gdp_australia = data.loc['Australia'] plt.plot(years, gdp_australia, 'g--')
Dapat memplot banyak kumpulan data secara bersamaan
# 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 ($)')
Menambahkan Legenda
Seringkali ketika memplot beberapa kumpulan data pada gambar yang sama, diinginkan untuk memiliki legenda yang menggambarkan data tersebut
Ini dapat dilakukan dalam time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _9 dalam dua tahap
- Berikan label untuk setiap dataset pada gambar
plt.plot(years, gdp_australia, label='Australia') plt.plot(years, gdp_nz, label='New Zealand')
- Instruksikan time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _9 untuk membuat legenda
plt.legend()
Secara default matplotlib akan mencoba menempatkan legenda pada posisi yang sesuai. Jika Anda lebih suka menentukan posisi, ini dapat dilakukan dengan argumen 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 7, mis. g untuk menempatkan legenda di pojok kiri atas plot, tentukan 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 8
- Buat plot pencar yang menghubungkan PDB Australia dan Selandia Baru
- Gunakan 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() _9 atau data.T.plot() plt.ylabel('GDP per capita') 0
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') 0
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _1
Minima dan Maksimal
Isilah titik-titik di bawah ini untuk memplot PDB per kapita minimum dari waktu ke waktu untuk semua negara di Eropa. Ubah lagi untuk memplot PDB per kapita maksimum dari waktu ke waktu untuk Eropa
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _2
Larutan
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _3
Korelasi
Ubah contoh dalam catatan untuk membuat sebar plot yang menunjukkan hubungan antara PDB per kapita minimum dan maksimum di antara negara-negara di Asia untuk setiap tahun dalam kumpulan data. Hubungan apa yang Anda lihat (jika ada)?
Larutan
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _4
Tidak ada korelasi khusus yang dapat dilihat antara nilai PDB minimum dan maksimum dari tahun ke tahun. Sepertinya peruntungan negara-negara Asia tidak naik dan turun bersamaan
Anda mungkin mencatat bahwa variabilitas maksimum jauh lebih tinggi daripada minimum. Lihatlah indeks maksimum dan maks
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') 5
Larutan
Tampaknya variabilitas nilai ini disebabkan penurunan tajam setelah tahun 1972. Beberapa geopolitik sedang bermain mungkin?
Lebih Banyak Korelasi
Program singkat ini membuat plot yang menunjukkan korelasi antara PDB dan harapan hidup untuk tahun 2007, menormalkan ukuran penanda berdasarkan jumlah penduduk
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _6
Dengan menggunakan bantuan online dan sumber daya lainnya, jelaskan apa yang dilakukan setiap argumen untuk 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 replace(), which removes from the string the characters stated in the argument # This method works on strings, so we use replace() from Pandas Series.str vectorized string functions years = data.columns.str.replace('gdpPercap_', '') # Convert year values to integers, saving results back to dataframe data.columns = years.astype(int) data.loc['Australia'].plot() 1
Larutan
Tempat yang baik untuk melihat adalah dokumentasi untuk fungsi plot - help(data_all. merencanakan)
jenis - Seperti yang sudah terlihat, ini menentukan jenis plot yang akan digambar
x dan y - Nama kolom atau indeks yang menentukan data apa yang akan ditempatkan pada sumbu x dan y dari plot
s - Detail untuk ini dapat ditemukan di dokumentasi plt. menyebarkan. Angka tunggal atau satu nilai untuk setiap titik data. Menentukan ukuran titik-titik yang diplot
Menyimpan plot Anda ke file
Jika Anda puas dengan plot yang Anda lihat, Anda mungkin ingin menyimpannya ke file, mungkin untuk memasukkannya ke dalam publikasi. Ada fungsi di matplotlib. modul pyplot yang menyelesaikan ini. savefig. Memanggil fungsi ini, e. g. dengan
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _7
akan menyimpan angka saat ini ke file data.T.plot() plt.ylabel('GDP per capita') 2. Format file akan secara otomatis diambil dari ekstensi nama file (format lain adalah pdf, ps, eps dan svg)
Perhatikan bahwa fungsi dalam data.T.plot() plt.ylabel('GDP per capita') _3 merujuk ke variabel angka global dan setelah angka ditampilkan ke layar (e. g. dengan data.T.plot() plt.ylabel('GDP per capita') _4) matplotlib akan membuat variabel ini merujuk ke angka kosong baru. Oleh karena itu, pastikan Anda memanggil data.T.plot() plt.ylabel('GDP per capita') _5 sebelum plot ditampilkan ke layar, jika tidak, Anda mungkin menemukan file dengan plot kosong
Saat menggunakan bingkai data, data sering dibuat dan diplot ke layar dalam satu baris, dan data.T.plot() plt.ylabel('GDP per capita') 5 sepertinya bukan pendekatan yang memungkinkan. Satu kemungkinan untuk menyimpan gambar ke file kemudian ke
- simpan referensi ke angka saat ini dalam variabel lokal (dengan data.T.plot() plt.ylabel('GDP per capita') 7)
- panggil metode kelas data.T.plot() plt.ylabel('GDP per capita') _8 dari variabel itu
time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') _8
Membuat plot Anda dapat diakses
Setiap kali Anda membuat plot untuk masuk ke makalah atau presentasi, ada beberapa hal yang dapat Anda lakukan untuk memastikan bahwa setiap orang dapat memahami plot Anda.
Bagaimana Anda membuat fungsi plotting di Python?
Keluaran. .Tentukan sumbu x dan nilai sumbu y yang sesuai sebagai daftarPlot di atas kanvas menggunakan. plot() fungsiBeri nama sumbu x dan sumbu y menggunakan. xlabel() dan. fungsi ylabel()Beri judul pada plot Anda menggunakan. judul() fungsiTerakhir, untuk melihat plot Anda, kami menggunakan. tampilkan() fungsiBagaimana Anda memplot suatu fungsi?
Membuat Grafik Aturan Fungsi . Setelah Anda memasukkan nilai-nilai itu ke dalam persamaan, Anda akan mendapatkan nilai y. Nilai x dan nilai y membentuk koordinat Anda untuk satu titik. select x-values and plug them into the equation. Once you plug those values into the equation, you will get a y-value. Your x-values and your y-values make up your coordinates for a single point.Bagaimana cara kerja fungsi plot di Python?
Memplot titik x dan y . Secara default, fungsi plot() menarik garis dari titik ke titik. Fungsi mengambil parameter untuk menentukan titik dalam diagram. Parameter 1 adalah larik yang berisi titik-titik pada sumbu x. The plot() function is used to draw points (markers) in a diagram. By default, the plot() function draws a line from point to point. The function takes parameters for specifying points in the diagram. Parameter 1 is an array containing the points on the x-axis.Bisakah Matplotlib merencanakan suatu fungsi?
Matplotlib. plot. fungsi plot() menyediakan antarmuka terpadu untuk membuat berbagai jenis plot . Contoh paling sederhana menggunakan fungsi plot() untuk memplot nilai sebagai koordinat x,y dalam plot data.