1. 程式人生 > >python繪圖基礎

python繪圖基礎

簡單的繪圖:

import matplotlib.pyplot as plt   #也可以寫成:from matplotlib import pyplot as plt

x = [5,6,7,8]
y = [7,8,5,6]
plt.plot(x,y)                  #也可以直接plt.plot([5,6,7,8],[7,8,5,6])
plt.title('First Chart')       #中文會亂碼
plt.xlabel('x axis')
plt.ylabel('y axis')

plt.show()                    #顯示
新增元素:
import matplotlib.pyplot as plt

x = [5,6,7,8]
y = [7,8,5,6]

x1 = [2,5,3,9]
y1 = [5,2,9,3]

plt.plot(x,y,'b',linewidth = 2, label = 'Line1') #顏色有g r y b k(黑)  linewidth設定線條粗細,color='b'可簡寫‘b’
plt.plot(x1,y1,'r',linewidth = 3, label = 'Line2') #要新增圖列必須給繪製的這條線命名,否則無法新增圖例

plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')

plt.legend()     #新增圖例

plt.grid()      #新增網格,加顏色寫成plt.grid(color='k'),color=不可省略,什麼都不寫預設灰色,grid()等於grid(True),去除網格grid(False)
plt.show()
效果(大多影象元素也可以直接在圖片選項中直接修改):



散點圖:

import matplotlib.pyplot as plt

x = [5,6,7,8]
y = [7,8,5,6]

x1 = [2,5,3,9]
y1 = [5,2,9,3]

plt.scatter(x,y,color='b',label = 'Line1')    #使用scatter命令,改變顏色必須使用color=
plt.scatter(x1,y1,color='r',label = 'Line2')

plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')

plt.legend()

#plt.grid()

plt.show()

繪製柱狀圖:
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [7,8,5,6]

x1 = [5,6,7,8]
y1 = [5,2,9,3]

plt.bar(x,y,color='b',label = 'Line1')    #使用bar命令 改變顏色必須color=
plt.bar(x1,y1,color='r',label = 'Line2')

plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')

plt.legend()

#plt.grid()

plt.show()