所以我必须绘制一个图,但它必须只包括数百个实例中的前25个实例
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import csv
import numpy as np
data=pd.read_csv("data_korona_dki_x.txt",sep=",", nrows=3)
print(data)
print("Describe :",data.describe())
x=[]
y=[]
z=[]
xx=[]
with open("data_korona_dki_x.txt","r") as csvfile:
plots=csv.reader(csvfile,delimiter=",")
for row in plots:
x.append(row[0])
y.append(int(row[1]))
z.append(int(row[2]))
xx.append(int(row[3]))
fig,ax=plt.subplots()
ax.plot(x,y,marker="o",label="Kasus Baru")
ax.plot(x,z,marker="x",label="Meninggal")
ax.plot(x,xx,marker="+",label="Sembuh")
plt.title("Data Korona Jakarta")
plt.xlabel("Tanggal")
plt.ylabel("Jumlah")
plt.xticks(rotation=90)
legend=ax.legend(loc="upper left", shadow=True)
for i,j in zip(x,y):
ax.annotate('%s' %j,xy=(i,j),xytext=(4,0), textcoords='offset points')
for a,b in zip(x,z):
ax.annotate('%s' %b,xy=(a,b),xytext=(4,0), textcoords='offset points')
for d,e in zip(x,xx):
ax.annotate('%s' %e,xy=(d,e),xytext=(4,0), textcoords='offset points')
#plt.xticks(x)
#plt.yticks(y)
# move_figure(fig,50,50)
print(plt.show())
这是我使用的代码,但当我使用它时,图形由数百个数据组成,但我只需要显示前20个数据。我该怎么做?
这将阻止追加超过20行的数据。
with open("data_korona_dki_x.txt","r") as csvfile:
plots=csv.reader(csvfile,delimiter=",")
i = 0
for row in plots:
x.append(row[0])
y.append(int(row[1]))
z.append(int(row[2]))
xx.append(int(row[3]))
if i >= 20:
break
i += 1
只需对代码进行最小的更改:
你可以对数据进行切片,只使用你需要的部分:
ax.plot(x[:26],y[:26],marker="o",label="Kasus Baru")
或者只需要获得更少的数据:
for row in plots:
x.append(row[0])
y.append(int(row[1]))
z.append(int(row[2]))
xx.append(int(row[3]))
if len(x) == 25:
break
注意:你的问题在20到25之间切换。我用了25。更改为20应该足够简单。