亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python使用Matplotlib繪圖及設置實例(用python制圖)

 更新時間:2022年05月14日 17:00:10   作者:Zincy星辰  
Python matplotlib包可以畫各種類型的圖,功能非常齊全,下面這篇文章主要給大家介紹了關于python使用Matplotlib繪圖及設置的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下

# matplotlib提供快速繪圖模塊pyplot,它模仿了MATLAB的部分功能

import matplotlib.pyplot as plt? ? ? ? #導入繪圖模塊

from matplotlib import pyplot as plt? ? ? ? ? ?#兩種導入方法都可

第一節(jié)內(nèi)容的精簡版總結(jié):

  1. 繪制折線圖(plt.plot)
  2. 設置圖片大小和分辨率(plt.figure)
  3. 保存圖片到本地(plt.savefig)
  4. 設置xy軸刻度和字符串(xticks、yticks)
  5. 設置標題、xy軸標簽(title、xlable、ylable)
  6. 設置字體(font_manager.fontProperties,matplotlib.rc)
  7. 同一張圖繪制多線條(plt多次plot)
  8. 添加圖例、繪制網(wǎng)格
  9. 其他圖像類型(散點圖plt.scatter,條形圖plt.bar,橫向plt.barh,直方圖plt.hist(bin.width組距、num_bins分多少組、))

一、初識matplotlib.pyplot

準備好制圖數(shù)據(jù),傳入?yún)?shù)。即可使用plt.plot(參數(shù))、plt.show()一鍵出圖!

import matplotlib.pyplot as plt
x = [......]
y = [......]
plt.plot(x,y,label='圖例')? ? ? ? #繪圖,并且標注圖例
plt.show()? ? ? ? #顯示
plot.legend(prop=my_font)? ? ? ? #設置顯示圖例,括號中意思為顯示中文(后面講解)

1.繪制圖像

plt.plot() 參數(shù)設置:

  • color=’ ‘        線條顏色
  • linestyle=’‘        線條風格
  • linewidth=        線條粗細
  • alpha=0.5        透明度        (對照表見常見繪圖屬性設置附表)

一個實例:假設一天中每隔兩個小時(range(2,26,2))的氣溫(℃)分別是[15,13,14.5,17,20,25,26,26,27,22,18,15]

import matplotlib.pyplot as plt
 
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]
 
# 繪圖
plt.plot(x,y)
# 顯示
plt.show()

繪制出如下圖片:

2.設置圖片大小

在繪制圖片之前,使用plt.figure函數(shù)設置圖片大小,其中figsize為元組,分別代表長寬,dpi(Dot Per Inch)為分辨率表示的單位之一。

plt.figure(figsize=(20,8),dpi=150)        #圖片大小為20*8,每英寸150個像素點

3.保存圖片文件

plt.savefig("./t1.png")        #將圖片保存到本地

引號里為文件路徑和文件名( ./ 代表當前路徑,png為文件后綴/格式)

4.設置X,Y軸刻度范圍

設置x,y軸的范圍可以使用多種方法

plt.xticks(x)? ? ? ? # 將x里的值作為刻度
plt.xticks(range(2,25))? ? ? ? #傳入range數(shù)列
plt.yticks(range(min(y),max(y)+1))? ? ? ? #傳入最小到最大值數(shù)列
_xticks_lables = [i/2 for i in range(4,49)]? ? ? ? ? ? ? ? # 生成更復雜的數(shù)列
plt.xticks(_xticks_lables[::3])? ? ? ? #取步長作為刻度

自定義刻度內(nèi)容

_x =list(x) [::3]
_xticks_labels = ["10點{ }分".format(i) for i in _x]
plt.xticks(_x,_xticks_labels)? ? ? ? #分別代表刻度范圍和刻度內(nèi)容

5.添加描述信息(標題、軸標簽)

plt.title("折線圖") ? ?#設置標題
plt.xlabel("時間") ? ?#設置x軸標注
plt.ylabel("氣溫") ? ?#設置y軸標注

6.設置顯示中文(導入字體模塊)

from matplotlib import font_manager????????#導入字體管理模塊
my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")
#定義中文字體屬性,文字儲存路徑可以在C:/WINDOWS/Fonts/找到,這里設置為宋體
plt.xlabel("時間",fontproperties = my_font,fontsize = 18)
#在設置x坐標中文標注,令fontproperties = my_font,fontsize令字體為18號
#plt.title,plt.ylabel,plt.xticks,plt.yticks設置中文標注類似

7.繪制網(wǎng)格

plt.grid(alpha=0.4)

繪制一個溫度隨時間變化的折線圖實例

import matplotlib.pyplot as plt
import random    #導入隨機生成模塊
from matplotlib import font_manager#導入字體管理模塊
my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")
#定義中文字體屬性,文字儲存路徑可以在C:/WINDOWS/Fonts/找到,本次設置為宋體
 
x = range(0,120)    #x值為0-120
y = [random.randint(20,35) for i in range(120)]     #y值為120個在20-35之間的隨機數(shù)
 
plt.figure(figsize=(15,10),dpi = 80)    #圖片大小為15*10,每英寸80個像素點
 
'''調(diào)整x軸刻度'''
_xticks_labels = ["10點{}分".format(i) for i in range(60)]
_xticks_labels += ["11點{}分".format(i) for i in range(60,120)]
plt.xticks(list(x)[::5],_xticks_labels[::5],rotation=45)    #rotation旋轉(zhuǎn)度數(shù)
#取步長5,數(shù)字和字符串一一對應,保證數(shù)據(jù)的長度一樣
 
'''設置標注'''
plt.title("10點到12點每分鐘溫度變化圖",fontproperties = my_font,fontsize = 24)    #設置標題
plt.xlabel("時間",fontproperties = my_font,fontsize = 18)    #設置x坐標標注,字體為18號
plt.ylabel("每分鐘對應的溫度",fontproperties = my_font,fontsize = 18)    #設置y坐標標注
 
plt.plot(x,y)   #繪圖
plt.show()  #顯示

二、常見繪圖屬性設置

1.繪圖符號(Makers)

符號

中文說明

英文說明

'.'

圓點

point marker

','

像素點

pixel marker

'o'

圓圈

circle marker

'v'

向下三角形

triangle_down marker

'^'

向上三角形

triangle_up marker

'<'

向左三角形

triangle_left marker

'>'

向右三角形

triangle_right marker

'1'

向下Y形

tri_down marker

'2'

向上Y形

tri_up marker

'3'

向左Y形

tri_left marker

'4'

向右Y形

tri_right marker

's'

方形

square marker

'p'

五邊形

pentagon marker

'*'

星形

star marker

'h'

六角形1

hexagon1 marker

'H'

六角形2

hexagon2 marker

'+'

加號

plus marker

'x'

叉號

x marker

'D'

鉆石形

diamond marker

'd'

鉆石形(?。?/p>

thin_diamond marker

'|'

豎線

vline marker

'_'

橫線

hline marker

2.線型(Line Styles)

符號

中文說明

英文說明

'-'

實線

solid line style

'--'

虛線

dashed line style

'-.'

點劃線

dash-dot line style

':'

點線

dotted line style

3.顏色縮寫(Colors)

多種豐富的顏色對照代碼參見:RGB顏色值與十六進制顏色碼轉(zhuǎn)換工具 (sioe.cn)

符號

中文說明

英文說明

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

4.Windows字體中英文名稱對照

中文名稱

英文名稱

黑體

SimHei

微軟雅黑

Microsoft YaHei

微軟正黑體

Microsoft JhengHei

新宋體

NSimSun

新細明體

PMingLiU

細明體

MingLiU

標楷體

DFKai-SB

仿宋

FangSong

楷體

KaiTi

仿宋_GB2312

FangSong_GB2312

楷體_GB2312

KaiTi_GB2312

面向?qū)ο蠓绞嚼L圖

  • matplotlib是一套面向?qū)ο蟮睦L圖庫,圖中的所有部件都是python對象。
  • pyplot是matplotlib仿照MATLAB提供的一套快速繪圖API,它并不是matplotlib本體。
  • pyplot雖然用起來簡單快捷,但它隱藏了大量的細節(jié),不能使用一些高級功能。
  • pyplot模塊內(nèi)部保存了當前圖表和當前子圖等信息,可以分別用gcf()和gca()獲得這兩個對象:
    • plt.gcf(): "Get current figure"獲取當前圖表(Figure對象)
    • plt.gca(): "Get current figure"獲取當前子圖(Axes對象)
  • pyplot中的各種繪圖函數(shù),實際上是在內(nèi)部調(diào)用gca獲取當前Axes對象,然后調(diào)用Axes的方法完成繪圖的。
import matplotlib.pyplot as plt
# 獲取當前的Figure和Axes對象
plt.figure(figsize=(4,3))
fig = plt.gcf()
axes = plt.gca()
print(fig)
print(axes)

配置對象的屬性

matplotlib所繪制的圖表的每一部分都對應一個對象,有兩種方式設置這些對象的屬性:

                通過對象的set_*()方法設置。

                通過pyplot的setp()方法設置。

同樣也有兩種方法查看對象的屬性:

                通過對象的get_*()方法查看。

                通過pyplot的getp()方法查看。

import matplotlib.pyplot as plt
import numpy as np
# 獲取當前的Figure和Axes對象
plt.figure(figsize=(4,3))
fig = plt.gcf() ; axes = plt.gca()
print(fig); print(axes)
x = np.arange(0, 5, 0.1)
# 調(diào)用plt.plot函數(shù),返回一個Line2D對象列表
lines = plt.plot(x, 0.05*x*x); print(lines)
# 調(diào)用Line2D對象的set系列方法設置屬性值
# 用set_alpha設置alpha通道,也就是透明度
lines[0].set_alpha(0.5) ; plt.show()
# plt.plot函數(shù)可以接受不定個數(shù)的位置參數(shù),這些位置參數(shù)兩兩配對,生成多條曲線。
lines = plt.plot(x, np.sin(x), x, np.cos(x), x, np.tanh(x))
plt.show()
# 使用plt.setp函數(shù)同時配置多個對象的屬性,這里設置lines列表中所有曲線的顏色和線寬。
plt.setp(lines, color='r', linewidth=4.0);plt.show()
# 使用getp方法查看所有的屬性
f = plt.gcf(); plt.getp(f)

import numpy as np
import matplotlib.pyplot as plt
# 獲取當前的Figure和Axes對象
plt.figure(figsize=(4,3))
fig = plt.gcf() ; axes = plt.gca()
print(fig); print(axes)
x = np.arange(0, 5, 0.1)
# 調(diào)用plt.plot函數(shù),返回一個Line2D對象列表
lines = plt.plot(x, 0.05*x*x); print(lines)
# 調(diào)用Line2D對象的set系列方法設置屬性值
# 用set_alpha設置alpha通道,也就是透明度
lines[0].set_alpha(0.5) ; plt.show()
# plt.plot函數(shù)可以接受不定個數(shù)的位置參數(shù),這些位置參數(shù)兩兩配對,生成多條曲線。
lines = plt.plot(x, np.sin(x), x, np.cos(x), x, np.tanh(x))
plt.show()
# 使用plt.setp函數(shù)同時配置多個對象的屬性,這里設置lines列表中所有曲線的顏色和線寬。
plt.setp(lines, color='r', linewidth=4.0);plt.show()
# 使用getp方法查看所有的屬性
f = plt.gcf(); plt.getp(f)
# 查看某個屬性
print(plt.getp(lines[0],"color"))
# 使用對象的get_*()方法
print(lines[0].get_linewidth())
# Figure對象的axes屬性是一個列表,存儲該Figure中的所有Axes對象。
# 下面代碼查看當前Figure的axes屬性,也就是gca獲得的當前Axes對象。
print(plt.getp(f, 'axes'))
print(len(plt.getp(f, 'axes')))
print(plt.getp(f, 'axes')[0] is plt.gca())
# 用plt.getp()可以繼續(xù)獲取AxesSubplot對象的屬性,例如它的lines屬性為子圖中的Line2D對象列表。
# 通過這種方法可以查看對象的屬性值,以及各個對象之間的關系。
all_lines = plt.getp(plt.gca(), "lines");print(all_lines)
plt.close() # 關閉當前圖表

 繪制多個子圖

在matplotlib中,一個Figure對象可以包括多個Axes對象(也就是子圖),一個Axes代表一個繪圖區(qū)域。最簡單的多子圖繪制方式是使用pyplot的subplot函數(shù)。

subplot(numRows, numCols, plotNum)接受三個參數(shù):

                numRows:子圖行數(shù)

                numCols:子圖列數(shù)

                plotNum:第幾個子圖(按從左到右,從上到下的順序編號)

import matplotlib.pyplot as plt
# 創(chuàng)建3行2列,共計6個子圖。
# subplot(323)等價于subplot(3,2,3)。
# 子圖的編號是從1開始,不是從0開始。
fig = plt.figure(figsize=(4,3))
for idx,color in enumerate('rgbcyk'):
    plt.subplot(321+idx, facecolor=color)
plt.show()
# 如果新創(chuàng)建的子圖和之前創(chuàng)建的有重疊區(qū)域,則之前的子圖會被刪除
plt.subplot(221)
plt.show()
plt.close()
# 還可以用多個高度或?qū)挾炔煌淖訄D相互拼接
fig = plt.figure(figsize=(4,3))
plt.subplot(221) # 第一行左圖
plt.subplot(222) # 第一行右圖
plt.subplot(212) # 第二行整行
plt.show()
plt.close()

三、Artist對象

簡單類型Artist對象是標準的繪圖元件,例如Line2D,Rectangle,Text,AxesImage等

容器類型Artist對象包含多個Artist對象使他們組織成一個整體例如Axis,Axes,F(xiàn)igure對象

Artist對象進行繪圖的流程

  • 創(chuàng)建Figure對象
  • 為Figure對象創(chuàng)建一個或多個Axes對象
  • 調(diào)用Axes對象的方法來創(chuàng)建各種簡單的Artist對象
import matplotlib.pyplot as plt
fig = plt.figure()
# 列表用于描述圖片所在的位置以及圖片的大小
ax = fig.add_axes([0.15, 0.1, 0.7, 0.3])
ax.set_xlabel('time')
line = ax.plot([1, 2, 3], [1, 2, 1])[0]
# ax的lines屬性是一個包含所有曲線的列表
print(line is ax.lines[0])
# 通過get_*獲得相應的屬性
print(ax.get_xaxis().get_label().get_text())
plt.show()

設置Artist屬性

 get_* 和 set_* 函數(shù)進行讀寫fig.set_alpha(0.5*fig.get_alpha())

Artist 屬性

作用

alpha

透明度,值在0到1之間,0為完全透明,1為完全不透明

animated

布爾值,在繪制動畫效果時使用

axes

此Artist對象所在的Axes對象,可能為None

clip_box

對象的裁剪框

clip_on

是否裁剪

clip_path

裁剪的路徑

contains

判斷指定點是否在對象上的函數(shù)

figure

所在的Figure對象,可能為None

label

文本標簽

picker

控制Artist對象選取

transform

控制偏移旋轉(zhuǎn)

visible

是否可見

zorder

控制繪圖順序

一些例子

import matplotlib.pyplot as plt
fig = plt.figure()
# 設置背景色
fig.patch.set_color('g')
# 必須更新界面才會有效果
fig.canvas.draw()
plt.show()
# artist對象的所有屬性都可以通過相應的get_*()和set_*()進行讀寫
# 例如設置下面圖像的透明度
line = plt.plot([1, 2, 3, 2, 1], lw=4)[0]
line.set_alpha(0.5)
line.set(alpha=0.5, zorder=1)
# fig.canvas.draw()
# 輸出Artist對象的所有屬性名以及與之對應的值
print(fig.patch)
plt.show()

 

import matplotlib.pyplot as plt
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('volts')
ax1.set_title('a sine wave')
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color='blue', lw=2)
# Fixing random state for reproducibility
np.random.seed(19680801)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
    facecolor='yellow', edgecolor='orange')
ax2.set_xlabel('time (s)')
plt.show()

 

 Figure容器

最上層的Artist對象是Figure,包含組成圖表的所有元素

Figure可以包涵多個Axes(多個圖表),創(chuàng)建主要有三種方法:

  • axes = fig.add_axes([left, bottom, width, height])
  • fig, axes = plt.subplots(行數(shù), 列數(shù))
  • axes = fig.add_subplot(行數(shù), 列數(shù), 序號)

Figure 屬性

說明

axes

Axes對象列表

patch

作為背景的Rectangle對象

images

FigureImage對象列表,用來顯示圖片

legends

Legend對象列表

lines

Line2D對象列表

patches

patch對象列表

texts

Text對象列表,用來顯示文字

import matplotlib.pyplot as plt
# 下面請看一個多Figure,多Axes,互相靈活切換的例子。
plt.figure(1) # 創(chuàng)建圖表1
plt.figure(2) # 創(chuàng)建圖表2
ax1 = plt.subplot(121) # 在圖表2中創(chuàng)建子圖1
ax2 = plt.subplot(122) # 在圖表2中創(chuàng)建子圖2
x = np.linspace(0, 3, 100)
for i in range(5):
    plt.figure(1) # 切換到圖表1
    plt.plot(x, np.exp(i*x/3))
    plt.sca(ax1) # 選擇圖表2的子圖1
    plt.plot(x, np.sin(i*x))
    plt.sca(ax2) # 選擇圖表2的子圖2
    plt.plot(x, np.cos(i*x))
    ax2.plot(x, np.tanh(i*x)) # 也可以通過ax2的plot方法直接繪圖
plt.show()
plt.close() # 打開了兩個Figure對象,因此要執(zhí)行plt.close()兩次
plt.close()
# 還可以使用subplots函數(shù),一次生成多個子圖,并返回Figure對象和Axes對象數(shù)組。
# 注意subplot和subplots兩個函數(shù)差一個s,前者是逐個生成子圖,后者是批量生成。
fig, axes = plt.subplots(2, 3, figsize=(4,3))
[a,b,c],[d,e,f] = axes
print(axes.shape)
print(b)
plt.show()
plt.close()

 

 Axes容器

  • 圖像的區(qū)域,有數(shù)據(jù)空間(標記為內(nèi)部藍色框)
  • 圖形可以包含多個 Axes,軸對象只能包含一個圖形
  • Axes 包含兩個(或三個)Axis對象,負責數(shù)據(jù)限制
  • 每個軸都有一個標題(通過set_title()設置)、一個x標簽(通過set_xLabel()設置)和一個通過set_yLabel()設置的y標簽集。

Axes 屬性

說明

artists

A list of Artist instances

patch

Rectangle instance for Axes background

collections

A list of Collection instances

images

A list of AxesImage

legends

A list of Legend instances

lines

A list of Line2D instances

patches

A list of Patch instances

texts

A list of Text instances

xaxis

matplotlib.axis.XAxis instance

yaxis

matplotlib.axis.YAxis instance

Axes的方法(Helper method)

所創(chuàng)建的對象(Artist )

添加進的列表(Container)

ax.annotate - text annotations

Annotate

ax.texts

ax.bar - bar charts

Rectangle

ax.patches

ax.errorbar - error bar plots

Line2D and Rectangle

ax.lines and ax.patches

ax.fill - shared area

Polygon

ax.patches

ax.hist - histograms

Rectangle

ax.patches

ax.imshow - image data

AxesImage

ax.images

ax.legend - axes legends

Legend

ax.legends

ax.plot - xy plots

Line2D

ax.lines

ax.scatter - scatter charts

PolygonCollection

ax.collections

ax.text - text

Text

ax.texts

 subplot2grid函數(shù)進行更復雜的布局。subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs)

  • shape為表示表格形狀的元組(行數(shù),列數(shù))
  • loc為子圖左上角所在的坐標元組(行,列)
  • rowspan和colspan分別為子圖所占據(jù)的行數(shù)和列數(shù) 
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,6))
ax1 = plt.subplot2grid((3,3),(0,0),colspan=2)
ax2 = plt.subplot2grid((3,3),(0,2),rowspan=2)
ax3 = plt.subplot2grid((3,3),(1,0),rowspan=2)
ax4 = plt.subplot2grid((3,3),(2,1),colspan=2)
ax5 = plt.subplot2grid((3,3),(1,1))
plt.show()
plt.close()

坐標軸上的刻度線、刻度文本、坐標網(wǎng)格及坐標軸標題等

set_major_*   set_minor_*

get_major_*   get_minor_*

import numpy as np
import matplotlib.pyplot as plt
# plt.figure creates a matplotlib.figure.Figure instance
fig = plt.figure()
rect = fig.patch # a rectangle instance
rect.set_facecolor('yellow')
ax1 = fig.add_axes([0.1, 0.3, 1,1])
rect = ax1.patch
rect.set_facecolor('orange')
for label in ax1.xaxis.get_ticklabels():
    # label is a Text instance
    label.set_color('red')
    label.set_rotation(45)
    label.set_fontsize(16)
for line in ax1.yaxis.get_ticklines():
    # line is a Line2D instance
    line.set_color('green')
    line.set_markersize(5)
    line.set_markeredgewidth(3)
plt.show()

 

坐標軸刻度設置

matplotlib會按照用戶所繪制的圖的數(shù)據(jù)范圍自動計算,但有的時候也需要我們自定義。

我們有時候希望將坐標軸的文字改為我們希望的樣子,比如特殊符號,年月日等。

# 修改坐標軸刻度的例子
# 配置X軸的刻度線的位置和文本,并開啟副刻度線
# 導入fractions包,處理分數(shù)
import numpy as np
import matplotlib.pyplot as plt
from fractions import Fraction
# 導入ticker,刻度定義和文本格式化都在ticker中定義
from matplotlib.ticker import MultipleLocator, FuncFormatter 
x = np.arange(0, 4*np.pi, 0.01)
fig, ax = plt.subplots(figsize=(8,4))
plt.plot(x, np.sin(x), x, np.cos(x))
# 定義pi_formatter, 用于計算刻度文本
# 將數(shù)值x轉(zhuǎn)換為字符串,字符串中使用Latex表示數(shù)學公式。
def pi_formatter(x, pos): 
    frac = Fraction(int(np.round(x / (np.pi/4))), 4)
    d, n = frac.denominator, frac.numerator
    if frac == 0:
        return "0"
    elif frac == 1:
        return "$\pi$"
    elif d == 1:
        return r"${%d} \pi$" % n
    elif n == 1:
        return r"$\frac{\pi}{%d}$" % d
    return r"$\frac{%d \pi}{%d}$" % (n, d)
# 設置兩個坐標軸的范圍
plt.ylim(-1.5,1.5)
plt.xlim(0, np.max(x))
# 設置圖的底邊距
plt.subplots_adjust(bottom = 0.15)
plt.grid() #開啟網(wǎng)格
# 主刻度為pi/4
# 用MultipleLocator以指定數(shù)值的整數(shù)倍放置刻度線
ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) )
# 主刻度文本用pi_formatter函數(shù)計算
# 使用指定的函數(shù)計算刻度文本,這里使用我們剛剛編寫的pi_formatter函數(shù)
ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) ) 
# 副刻度為pi/20
ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
# 設置刻度文本的大小
for tick in ax.xaxis.get_major_ticks():
    tick.label1.set_fontsize(16)
plt.show()
plt.close()

import datetime 
import numpy as np
import matplotlib.pyplot as plt
# 準備數(shù)據(jù)
x = np.arange(0,10,0.01)
y = np.sin(x)
# 將數(shù)據(jù)轉(zhuǎn)換為datetime對象列表
date_list = []
date_start = datetime.datetime(2000,1,1,0,0,0)
delta = datetime.timedelta(days=1)
for i in range(len(x)):
    date_list.append(date_start + i*delta)
# 繪圖,將date_list作為x軸數(shù)據(jù),當作參數(shù)傳遞
fig, ax = plt.subplots(figsize=(10,4))
plt.plot(date_list, y)
# 設定標題
plt.title('datetime example')
plt.ylabel('data')
plt.xlabel('Date')
plt.show()
plt.close()

 

如果數(shù)據(jù)中本來就有時間日期信息,可以使用strptime和strftime直接轉(zhuǎn)換。

使用strptime函數(shù)將字符串轉(zhuǎn)換為time,使用strftime將time轉(zhuǎn)換為字符串。

python中的時間日期格式化符號:

符號

意義

%y

兩位數(shù)的年份表示(00-99)

%Y

四位數(shù)的年份表示(000-9999)

%m

月份(01-12)

%d

月內(nèi)中的一天(0-31)

%H

24小時制小時數(shù)(0-23)

%I

12小時制小時數(shù)(01-12)

%M

分鐘數(shù)(00=59)

%S

秒(00-59)

%a

本地簡化星期名稱

%A

本地完整星期名稱

%b

本地簡化的月份名稱

%B

本地完整的月份名稱

%c

本地相應的日期表示和時間表示

%j

年內(nèi)的一天(001-366)

%p

本地A.M.或P.M.的等價符

%U

一年中的星期數(shù)(00-53)星期天為星期的開始

%w

星期(0-6),星期天為星期的開始

%W

一年中的星期數(shù)(00-53)星期一為星期的開始

%x

本地相應的日期表示

%X

本地相應的時間表示

%Z

當前時區(qū)的名稱

%%

%號本身

總結(jié)

到此這篇關于python使用Matplotlib繪圖及設置的文章就介紹到這了,更多相關python Matplotlib繪圖設置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論