溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中怎么使用Matplotlib繪制統(tǒng)計圖

發(fā)布時間:2021-11-26 09:33:40 來源:億速云 閱讀:270 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“Python中怎么使用Matplotlib繪制統(tǒng)計圖”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Python中怎么使用Matplotlib繪制統(tǒng)計圖”吧!

1.1 概述

Matplotlib是一個Python繪圖包,它使從存儲在各種數(shù)據(jù)結(jié)構(gòu)中的數(shù)據(jù)(包括列表、numpy數(shù)組和pandas數(shù)據(jù)框)創(chuàng)建二維圖變得簡單。Matplotlib使用了一種面向?qū)ο蟮睦L圖方法。這意味著可以通過向繪圖中添加新的元素來逐步構(gòu)建繪圖

matplotlib繪圖中主要會用到兩個對象:

figure對象:整體的圖空間,可以包含一個或多個子圖

axis對象:在圖空間中呈現(xiàn)的各個子圖,可以把figure對象看作是整個繪圖畫布,而axis對象看作是其中的一個子圖

一個圖空間可以容納一個或多個axis對象,這種結(jié)構(gòu)允許我們創(chuàng)建帶有一個或多個子圖的圖形

Python中怎么使用Matplotlib繪制統(tǒng)計圖

雖然Matplotlib包含許多模塊,提供不同的繪圖功能,但最常用的模塊是pyplot

Pyplot提供的方法可用于向圖形對象添加不同的組件,包括將各個圖創(chuàng)建為axis對象,也就是子圖

pyplot模塊通常使用別名plt導入,如下所示:

# Import pyplot
import matplotlib.pyplot as plt

1.2 使用Matplotlib創(chuàng)建圖像

要使用matplotlib的面向?qū)ο蠓椒▌?chuàng)建一個圖,首先要使用pyplot模塊中的subplots()函數(shù)創(chuàng)建一個圖(可以稱為fig)和至少一個軸(可以稱為ax)

fig, ax = plt.subplots()

請注意,通過將figax設(shè)置為等于pyplot.subplots()函數(shù)的輸出值,figax被同時創(chuàng)建。由于沒有提供其他參數(shù),結(jié)果是一個帶有一個空圖的圖

# Create figure and one plot (axis object) 
fig, ax = plt.subplots()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

1.3 更改圖片大小

使用figsize參數(shù)設(shè)置繪圖空間的寬和高

figsize = (width, height)

# Resize figure
fig, ax = plt.subplots(figsize = (10, 6))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

1.4 繪制多個子圖

使用matplotlib的面向?qū)ο蠓椒?,通過創(chuàng)建額外的axis對象,可以更容易地在圖空間中創(chuàng)建多個子圖 

Python中怎么使用Matplotlib繪制統(tǒng)計圖

當添加多個axis對象時,最好的做法是給它們不同的名稱(如ax1ax2),這樣就可以很容易地單獨使用每個axis

因此,需要為plt.subplots提供新的參數(shù),用于圖的布局:(行數(shù),列數(shù))

plt.subplots(1, 2)

在本例中,1、2表示布局為1行,2列

# Figure with two plots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (10, 6))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

相反地,(2,1)表示2行,1列格局分布

fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (10, 6))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

由于定義了figsize=(10,6),figure繪圖空間會保持這個大小,無論如何設(shè)置行數(shù)或列數(shù)是多少

但是,可以調(diào)整行數(shù)、列數(shù)以及figsize,以得到需要的大小

# Figure with two plots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (12, 12))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

可以根據(jù)需要繼續(xù)添加任意數(shù)量的axis對象,以創(chuàng)建所需圖形的整體布局,并根據(jù)需要繼續(xù)調(diào)整圖形大小

# Figure with three plots
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize = (15, 15))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

Matplotlib 面向?qū)ο蠓椒ǖ囊粋€主要優(yōu)點是,每個axis都是獨立的的對象,可以獨立于圖中的其他繪圖獨立地進行自定義繪制

2 使用 Matplotlib 繪制自定義圖表

在本章的前面,學習了如何使用pyplot中的subplot ()函數(shù)創(chuàng)建圖形和軸對象(使用別名plt導入) :

fig,ax = plt.subplots()

現(xiàn)在已經(jīng)知道如何使用matplotlib創(chuàng)建基本的繪圖,可以開始向圖中的繪圖添加數(shù)據(jù)了

首先導入別名pltmatplotlib.pyplot模塊,并創(chuàng)建一些列表來繪制由美國國家海洋和大氣管理局(NOAA)提供的*科羅拉多州博爾德市的月平均降水量(英寸)*

# Import pyplot 導入包
import matplotlib.pyplot as plt

# Monthly average precipitation 月平均降水量
boulder_monthly_precip = [0.70, 0.75, 1.85, 2.93, 3.05, 2.02, 
                          1.93, 1.62, 1.84, 1.31, 1.39, 0.84]

# Month names for plotting 月份
months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", 
          "Aug", "Sept", "Oct", "Nov", "Dec"]

2.1 使用 Matplotlib 繪制數(shù)據(jù)

可以通過調(diào)用所需的ax對象將數(shù)據(jù)添加到繪圖中,該對象是先前定義的axis元素:

fig,ax = plt.subplots()

通過調(diào)用ax對象的plot()方法,并指定繪圖的x軸(水平軸)和y軸(垂直軸)的參數(shù)如下

plot(x_axis, y_axis)

在這個例子中,你正在從之前定義的列表中添加數(shù)據(jù),數(shù)據(jù)沿著x軸和y軸分布

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip)
[<matplotlib.lines.Line2D at 0x7f0b21ed3e48>]

Python中怎么使用Matplotlib繪制統(tǒng)計圖

可以注意到,輸出顯示了圖形的對象類型以及唯一標識符(內(nèi)存位置)

[<matplotlib.lines.Line2D at 0x7f81afe900b8>]

可以通過在代碼末尾調(diào)用plt.show()來隱藏該信息

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months,boulder_monthly_precip)
    
plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.2 Matplotlib Plot 對象的命名約定

Python 社區(qū)中的慣例是使用ax來命名axis對象,但這并不是唯一的

# Define plot space with ax named bob
fig, bob = plt.subplots(figsize=(10, 6))

# Define x and y axes
bob.plot(months,boulder_monthly_precip)

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.3 創(chuàng)建不同類型的Matplotlib圖: 散點圖和條形圖

默認情況下,ax.plot 將繪圖創(chuàng)建為線圖(這意味著所有的值都通過橫跨繪圖的連續(xù)線連接起來)

可以使用 ax 對象來創(chuàng)建:

  • 散點圖(使用ax.scatter) : 值顯示為不連續(xù)線的單個點

  • 條形圖(使用ax.bar) : 值顯示為條形,其高度指示特定點的值

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Create scatter plot
ax.scatter(months,boulder_monthly_precip)

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Create bar plot
ax.bar(months,boulder_monthly_precip)

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.4 自定義繪圖標題和坐標軸標簽

可以使用ax.set()方法中的titlexlabelylabel參數(shù)為軸添加繪圖標題和標簽,從而自定義和添加更多信息到繪圖中

ax.set(title = "Plot title here",
       xlabel = "X axis label here", 
       ylabel = "Y axis label here")
# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip)

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation in Boulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation (inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.5 自定義多行繪圖標題和坐標軸標簽

使用兩個單詞之間的新行字符**\n**創(chuàng)建具有多行文本的標題和軸標簽

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip)

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.6 標簽旋轉(zhuǎn)

使用plt.setp函數(shù)設(shè)置整個繪圖空間的參數(shù),如自定義刻度標簽

在下面的例子中,ax.get_xticklabels()函數(shù)控制x軸的刻度標簽,rotation

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip)

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.setp(ax.get_xticklabels(),rotation=45)

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.7 自定義折線、點標記形狀

可以通過marker=參數(shù)對線段、點的形狀標識進行修改

Marker symbolMarker description
.point
,pixel
ocircle
vtriangle_down
^triangle_up
<triangle_left
>triangle_right

訪問Matplotlib文檔可以獲取更多標記類型列表

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.scatter(months, 
        boulder_monthly_precip,
        marker = ',') # pixel

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip,
        marker = 'o') # point

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.8 自定義繪圖顏色

可以使用color參數(shù)自定義繪圖顏色,在matplotlib中提供的一些基本顏色選項列表如下:

    b: blue
    g: green
    r: red
    c: cyan
    m: magenta
    y: yellow
    k: black
    w: white

對于這些基本顏色,可以將color參數(shù)設(shè)置為等于全名(例如cyan)或者僅僅是如上表所示的鍵字母(例如c)

要獲得更多的顏色,請訪問關(guān)于顏色的matplotlib文檔

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.plot(months, 
        boulder_monthly_precip,
        marker = 'o',
        color = 'cyan') # color=c

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.scatter(months, 
        boulder_monthly_precip,
        marker = ',',
        color = 'k') # color=black

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.bar(months, 
        boulder_monthly_precip,
        color = 'darkblue')

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.8 設(shè)置顏色透明度

使用alpha =參數(shù)調(diào)整顏色的透明度,其值接近0.0表示更高的透明度

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.bar(months, 
       boulder_monthly_precip,
       color = 'darkblue', 
       alpha = 0.3) # 透明度設(shè)置

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.9 自定義條形圖的顏色

通過使用參數(shù)edgeccolor=將每個條的輪廓顏色更改為藍色,并從前面討論過的matplotlib顏色選項中指定一種顏色,可以進一步自定義條形圖

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.bar(months, 
       boulder_monthly_precip,
       color = 'cyan',
       edgecolor = 'darkblue') # 輪廓顏色設(shè)置

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.10 自定義散點圖的顏色

在使用散點圖時,還可以使用ccmap參數(shù)根據(jù)每個點的數(shù)據(jù)值為其分配一種顏色

c參數(shù)允許指定將被顏色映射的值序列(例如boulder _ monthly _ precip) ,而cmap允許指定用于該序列的顏色映射

下面的例子使用了YlGnBu顏色圖,其中較低的值用黃色到綠色色調(diào)填充,而較高的值用越來越深的藍色色調(diào)填充

要查看彩色地圖選項列表,請訪問的matplotlib cmpas文檔

# Define plot space
fig, ax = plt.subplots(figsize=(10, 6))

# Define x and y axes
ax.scatter(months, 
        boulder_monthly_precip,
        c = boulder_monthly_precip,
        cmap = 'YlGnBu')

# Set plot title and axes labels
ax.set(title = "Average Monthly Precipitation\nBoulder, CO",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.11 將數(shù)據(jù)繪制為多圖

回想matplotlib的面向?qū)ο蠓椒?,通過創(chuàng)建額外的axis對象,可以很容易地在一個圖形中包含多個圖形:

fig, (ax1, ax2) = plt.subplots(num_rows, num_columns)

一旦定義了fig和兩個axis對象,就可以向每個軸添加數(shù)據(jù)并定義具有獨特特征的圖形

在下面的示例中,ax1.bar在第一個繪圖中創(chuàng)建一個定制的條形圖,而ax2.scatter在第二個繪圖中創(chuàng)建一個定制的散點圖

# Define plot space
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12)) # 兩行一列

# Define x and y axes
ax1.bar(months, 
       boulder_monthly_precip,
       color = 'cyan', 
       edgecolor = 'darkblue')

# Define x and y axes
ax2.scatter(months, 
        boulder_monthly_precip,
        c = boulder_monthly_precip,
        cmap = 'YlGnBu')

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.12 為多個子圖添加標題和軸標簽

可以繼續(xù)添加ax1ax2,例如為每個單獨的繪圖添加標題和軸標簽,就像您以前只有一個繪圖時所做的那樣

可以使用ax1.set()為第一個繪圖(柱狀圖)定義元素,使用ax2.set()為第二個繪圖(散點圖)定義元素

# Define plot space
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))

# Define x and y axes
ax1.bar(months, 
       boulder_monthly_precip,
       color = 'cyan', 
       edgecolor = 'darkblue')

# Set plot title and axes labels
ax1.set(title = "Bar Plot of Average Monthly Precipitation",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)");

# Define x and y axes
ax2.scatter(months, 
        boulder_monthly_precip,
        c = boulder_monthly_precip,
        cmap = 'YlGnBu')

# Set plot title and axes labels
ax2.set(title = "Scatter Plot of Average Monthly Precipitation",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

現(xiàn)在已經(jīng)有了多個圖形(每個圖形都有自己的標簽) ,還可以為整個圖形添加一個總體標題(使用指定的字體大小) ,使用:

fig.suptitle("Title text", fontsize = 16)

# Define plot space
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))

fig.suptitle("Average Monthly Precipitation for Boulder, CO", fontsize = 16)

# Define x and y axes
ax1.bar(months, 
       boulder_monthly_precip,
       color = 'cyan', 
       edgecolor = 'darkblue')

# Set plot title and axes labels
ax1.set(title = "Bar Plot",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)");

# Define x and y axes
ax2.scatter(months, 
        boulder_monthly_precip,
        c = boulder_monthly_precip,
        cmap = 'YlGnBu')

# Set plot title and axes labels
ax2.set(title = "Scatter Plot",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

2.13 將 Matplotlib 圖形保存為圖像文件

可以使用以下命令輕松地將圖形保存到圖像文件中,例如 .png:

plt.savefig ("path/name-of-file.png")

可以保存最新的數(shù)據(jù),如果沒有為文件指定一個路徑,文件將會在你當前的工作目錄文件夾中創(chuàng)建

查看Matplotlib文檔以查看用于保存圖形的其他文件格式的列表

# Define plot space
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))

fig.suptitle("Average Monthly Precipitation for Boulder, CO", fontsize = 16)

# Define x and y axes
ax1.bar(months, 
       boulder_monthly_precip,
       color = 'cyan', 
       edgecolor = 'darkblue')

# Set plot title and axes labels
ax1.set(title = "Bar Plot",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)");

# Define x and y axes
ax2.scatter(months, 
        boulder_monthly_precip,
        c = boulder_monthly_precip,
        cmap = 'YlGnBu')

# Set plot title and axes labels
ax2.set(title = "Scatter Plot",
       xlabel = "Month",
       ylabel = "Precipitation\n(inches)")

plt.savefig("output/average-monthly-precip-boulder-co.png")

plt.show()

2.14 額外資源

  • 關(guān)于顏色條的更多信息color bars

  • 深入介紹matplotlib

3.1 自定義x軸日期刻度

# Import required python packages
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
import seaborn as sns
import earthpy as et

# Date time conversion registration
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Get the data
# data = et.data.get_data('colorado-flood')

# Set working directory
os.chdir(os.path.join(et.io.HOME, 'learning','python_data_plot'))

# Prettier plotting with seaborn
sns.set(font_scale=1.5)
sns.set_style("whitegrid")

在本節(jié)中,將學習如何在Python中使用matplotlib繪制時間序列

# Read in the data
data_path = "data/precipitation/805325-precip-dailysum-2003-2013.csv"
boulder_daily_precip = pd.read_csv(data_path,
                                   parse_dates=['DATE'], # 將csv中的時間字符串轉(zhuǎn)換成日期格式
                                   na_values=['999.99'],
                                   index_col=['DATE'])
boulder_daily_precip.head()

<div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }

.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

</style> <table border="1" class="dataframe"> <thead> <tr > <th></th> <th>DAILY_PRECIP</th> <th>STATION</th> <th>STATION_NAME</th> <th>ELEVATION</th> <th>LATITUDE</th> <th>LONGITUDE</th> <th>YEAR</th> <th>JULIAN</th> </tr> <tr> <th>DATE</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>2003-01-01</th> <td>0.0</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.03389</td> <td>-105.28111</td> <td>2003</td> <td>1</td> </tr> <tr> <th>2003-01-05</th> <td>NaN</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.03389</td> <td>-105.28111</td> <td>2003</td> <td>5</td> </tr> <tr> <th>2003-02-01</th> <td>0.0</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.03389</td> <td>-105.28111</td> <td>2003</td> <td>32</td> </tr> <tr> <th>2003-02-02</th> <td>NaN</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.03389</td> <td>-105.28111</td> <td>2003</td> <td>33</td> </tr> <tr> <th>2003-02-03</th> <td>0.4</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.03389</td> <td>-105.28111</td> <td>2003</td> <td>34</td> </tr> </tbody> </table> </div>

# Subset the data 
# 提取8月15至10月15之間的數(shù)據(jù)
precip_boulder_AugOct = boulder_daily_precip["2013-08-15":"2013-10-15"]


# View first few rows of data
precip_boulder_AugOct.head()

<div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }

.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

</style> <table border="1" class="dataframe"> <thead> <tr > <th></th> <th>DAILY_PRECIP</th> <th>STATION</th> <th>STATION_NAME</th> <th>ELEVATION</th> <th>LATITUDE</th> <th>LONGITUDE</th> <th>YEAR</th> <th>JULIAN</th> </tr> <tr> <th>DATE</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>2013-08-21</th> <td>0.1</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.0338</td> <td>-105.2811</td> <td>2013</td> <td>233</td> </tr> <tr> <th>2013-08-26</th> <td>0.1</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.0338</td> <td>-105.2811</td> <td>2013</td> <td>238</td> </tr> <tr> <th>2013-08-27</th> <td>0.1</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.0338</td> <td>-105.2811</td> <td>2013</td> <td>239</td> </tr> <tr> <th>2013-09-01</th> <td>0.0</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.0338</td> <td>-105.2811</td> <td>2013</td> <td>244</td> </tr> <tr> <th>2013-09-09</th> <td>0.1</td> <td>COOP:050843</td> <td>BOULDER 2 CO US</td> <td>1650.5</td> <td>40.0338</td> <td>-105.2811</td> <td>2013</td> <td>252</td> </tr> </tbody> </table> </div>

fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(precip_boulder_AugOct.index.values,
        precip_boulder_AugOct['DAILY_PRECIP'].values,
        '-o',
        color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)",
       title="Daily Precipitation \nBoulder, Colorado 2013")

# Format the x axis
# 對x軸進行日期格式化
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))
ax.xaxis.set_major_formatter(DateFormatter("%m-%d"))

plt.show()

Python中怎么使用Matplotlib繪制統(tǒng)計圖

3.2 對Matplotlib進行日期格式化

在 matplotlib 中,也可以使用 DateFormatter 模塊更改繪圖軸上的日期格式

需要從 matplotlib 導入 DateFormatter,然后使用以下語法指定日期 DateFormatter 要使用的格式:

%Y-4位數(shù)年份 %y-2位數(shù)年份 %m-月份 %d-天

實現(xiàn)自定義日期的步驟:

  • 定義日期格式: myFmt = DateFormatter("%m/%d"),這個日期格式是月/日,所以它看起來像這樣: 10/05,代表10月5日

  • 調(diào)用set_major_formatter()方法:

ax.xaxis.set_major_formatter(myFmt)

將上面定義的日期格式應用于繪圖空間中

# Plot the data
fig, ax = plt.subplots(figsize=(10,6))
ax.scatter(precip_boulder_AugOct.index.values,
           precip_boulder_AugOct['DAILY_PRECIP'].values,
           color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)",
       title="Daily Precipitation (inches)\nBoulder, Colorado 2013")

# Define the date format
date_form = DateFormatter("%m/%d")
ax.xaxis.set_major_formatter(date_form)

Python中怎么使用Matplotlib繪制統(tǒng)計圖

3.3 X軸的日期刻度

特定的時間刻度可以沿著x軸添加,例如:大的刻度可以表示每個新的工作周的開始,小的刻度可以表示每個工作日

函數(shù)xaxis.set_major_locator()控制大刻度的位置,函數(shù)xaxis.set_minor_locator控制小刻度

# Plot the data
fig, ax = plt.subplots(figsize=(10,6))
ax.scatter(precip_boulder_AugOct.index.values,
           precip_boulder_AugOct['DAILY_PRECIP'].values,
           color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)",
       title="Daily Precipitation (inches)\nBoulder, Colorado 2013")

# 定義日期格式
date_form = DateFormatter("%m/%d")
ax.xaxis.set_major_formatter(date_form)
# 確保每隔一周刻度減小一次
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
# ax.xaxis.set_minor_locator(mdates.DayLocator(1))

Python中怎么使用Matplotlib繪制統(tǒng)計圖

到此,相信大家對“Python中怎么使用Matplotlib繪制統(tǒng)計圖”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI