【Python】matplotlib繪制折線圖
阿新 • • 發佈:2017-12-03
圖片 add 但我 修復 put inline Coding 嘗試 ram
一、繪制簡單的折線圖
import matplotlib.pyplot as plt squares=[1,4,9,16,25] plt.plot(squares) plt.show()
我們首先導入模塊pylot,並給他指定別名plt,然後創建列表,存儲前述的平方數,再將這個列表傳遞給函數plot(),這個函數嘗試根據這些數字繪制出有意義的圖形。plot.show()打開matplotlib查看器,並顯示繪制圖形。
運行結果:
二、修改標簽文字和線條粗細
#coding:UTF-8 import matplotlib.pyplot as plt squares=[1,4,9,16,25] plt.plot(squares,linewidth= 5) #設置圖形的標題,並給坐標軸加上標簽 plt.title("Squares Numbers",fontsize=24) plt.xlabel("Value",fontsize=14) plt.ylabel("Square of value",fontsize=14) #設置刻度表標記的大小 plt.tick_params(axis="both",labelsize=14) plt.plot(squares) plt.show()
title():給圖表指定標題
xlabel():給X軸設置標題
ylabel():給Y軸設置標題
tick_params():設置刻度的樣式
運行結果:
校正圖形
從上面的圖形可以看出:折線圖的終點4對應的平方為25,下面來修復這個問題
當你向plot()提供一系列數字時,它假設第一個數據點對應的x坐標軸值為0,但我們的第一個坐標軸對應的x軸為1,為了改變這種默認行為,我們可以給plot()同時提供輸入值和輸出值
#coding:UTF-8 import matplotlib.pyplot as plt input_value = [1,2,3,4,5] squares=[1,4,9,16,25] plt.plot(input_value,squares,linewidth = 5) #設置圖形的標題,並給坐標軸加上標簽plt.title("Squares Numbers",fontsize=24) plt.xlabel("Value",fontsize=14) plt.ylabel("Square of value",fontsize=14) #設置刻度表標記的大小 plt.tick_params(axis="both",labelsize=14) plt.show()
運行結果:
【Python】matplotlib繪制折線圖