问题描述
我想创建一个包含800行的数据框的散点图。我不想将它们绘制在整个图形中,而是要用数据行的15行将图形分开。我应该看到54张图。 如何使用python做到这一点?
解决方法
我创建了一些随机数据,数据框中有两列。然后,您可以使用numpy遍历数据帧的每15行(不要使用DataFrame.iterrows
,因为它效率极低),并为每个数据块创建一个简单的散点图。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(1234)
data = np.random.rand(800,2)
df = pd.DataFrame(data=data,columns=['x','y'])
## split the dataframe into 54 chunks,this is hardcoded since you specified that your dataframe contains 800 rows = 15 rows x 54
for index,df_chunk in enumerate(np.array_split(df,54)):
plt.scatter(df_chunk.x,df_chunk.y)
## this will immediately save 54 scatter plots,numbered 1-54,be warned!
plt.title('Scatter Plot #' + str(index+1))
plt.savefig('./scatter_plot_' + str(index+1) + '.png')
## clear the figure
plt.clf()
下面,我列出了创建的54个散点图之一。可以随意修改标题,x轴和y轴标题,标记颜色和类型。