Matplotlib從文件繪圖時Y軸座標不正確

問題描述:app

從文件中讀取X座標和Y座標,繪製折線圖,代碼和結果以下:spa

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style


    
style.use('dark_background')

fig = plt.figure()



graph_data = open('example.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
    if len(line) > 1:
        x, y = line.split(',')
        xs.append(x)
        ys.append(y)

plt.plot(xs, ys)
plt.show()

 

解決:code

我想這種bug也只有計算機專業能想到吧。。。blog

那就是——類型錯誤!從文件中讀到的每一個x和y爲字符串,應該轉換成int類型。改正後:字符串

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style


    
style.use('dark_background')

fig = plt.figure()



graph_data = open('example.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
    if len(line) > 1:
        x, y = line.split(',')
        xs.append(int(x)) #注意讀取到的是字符串類型
        ys.append(int(y)) 

plt.plot(xs, ys)
plt.show()

相關文章
相關標籤/搜索