【问题标题】:How can I print different scatter plots in a For loop in pandas?如何在熊猫的 For 循环中打印不同的散点图?
【发布时间】:2019-10-21 13:14:42
【问题描述】:

我正在尝试使用 python 在不同的行中绘制 3D 散点图。

数组“seasons”包含四个不同的数据集,我正在尝试调用每个数据集并分别绘制 3D 散点图。

下面的代码只给了我一个数据集季节的结果[df]。

seasons = [summer_spike_df,Autumn_spike_df,Winter_spike_df,Spring_spike_df]
colors = ['b', 'orange', 'g', 'r', 'c', 'm', 'y', 'k', 'Brown', 'ForestGreen'] 
ncenters = 3

for df in (seasons):
    alldata = np.vstack((df['time_of_day'], df['Height'],df['resolution']))
    cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(
        alldata, ncenters, 3, error=0.005, maxiter=1000, init=None)
    fpcs = []
    fpcs.append(fpc)
    for pt in cntr:
        ax.scatter(pt[0], pt[1],pt[2],color='r')

    cluster_membership = np.argmax(u, axis=0)
    for j in range(ncenters):
        ax.scatter(df['time_of_day'][cluster_membership == j],
                df['Height'][cluster_membership == j],
                df['resolution'][cluster_membership == j],
                '.', 
                color=colors[j], edgecolor='k',marker='o', s=20, lw=0, alpha=0.7)

ax.set_title('Centers = {0}; FPC = {1:.2f}'.format(ncenters, fpc))
ax.axis('on')
#ax.set_ylim([0,6])
ax.grid()
plt.show()

如果我将 plt.show()plt.close() 放在 for 循环之外,那么它会在同一个图中显示所有散点图。

【问题讨论】:

    标签: python for-loop matplotlib 3d scatter-plot


    【解决方案1】:

    您没有显示您定义ax 的位置。但是,要将数据集放入单独的 3d 散点图中,您需要在单独的轴中定义它们。

    例如,您可以在一个图中定义 4 个单独的 Axes,并将每个数据帧显式绘制到单独的 Axes 中:

    fig, axes = plt.subplots(nrows=2, ncols=2)
    for df, ax in zip(seasons, axes.flatten()):
        # Your for loop will probably work as is here
        ...
    
        # With this exception, you'll just move code below within for loop
        ax.set_title('Centers = {0}; FPC = {1:.2f}'.format(ncenters, fpc))
        ax.axis('on')
        ax.grid()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2013-10-03
      • 2020-11-16
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多