【问题标题】:Subplots repeating the same graph 6 times and producing 6 figures instead of one子图重复相同的图表 6 次并生成 6 个图形而不是 1 个图形
【发布时间】:2021-11-24 18:50:02
【问题描述】:

所以我有这个代码:

def scatter(df, column_name):
  values = {data: list(df[data]) for data in column_name}

  data = list(values.values())
  labels = list(values.keys())
  
  for i in range(len(data)):
    for j in range(len(data)):
      if i == j:
        continue
      elif (i == 1) & (j == 0):
        continue
      elif (i == 2) & ((j == 0)|(j == 1)):
        continue
      elif (i == 3) & ((j == 0)|(j == 1)|(j == 2)):
        continue
      else:
        for k in range(6):
          ax = plt.subplot(3, 2, k+1)
          plt.scatter(data[i], data[j])
          plt.xlabel(labels[i])
          plt.ylabel(labels[j])
          plt.title('{} vs {}'.format(labels[i], labels[j]))
        plt.show()
        plt.clf()

scatter(roller_coasters, ['speed', 'height', 'length', 'num_inversions'])

但它产生 6 个数字而不是 1 个,并且每个数字都有相同的图形重复 6 次。

请帮我解决这个问题。

【问题讨论】:

    标签: python for-loop matplotlib plot subplot


    【解决方案1】:

    每次输入循环的else 部分时,都会为给定的i,j 组合创建6 个子图。例如。对于i=0; j=1k 的循环创建六个子图,但仅针对特定的ij。当创建时,图形再次关闭(plt.clf())。以下i=0; j=2 创建了下一组 6 个子图。

    您可以通过让j 上的循环从i+1 开始来简化事情,因此不需要测试。此外,接下来将为其创建子图的值可以是变量k,每次添加子图时都会递增。

    下面是一些示例代码:

    from matplotlib import pyplot as plt
    import pandas as pd
    import numpy as np
    
    def scatter(df, column_names):
        fig = plt.figure(figsize=(10, 12)) # set a size for the surrounding plot
        n = len(column_names)
        total = n * (n - 1) // 2
        ncols = 2
        nrows = (total + (ncols - 1)) // ncols
        k = 1
        for i in range(n):
            col_i = column_names[i]
            for j in range(i + 1, n):
                col_j = column_names[j]
                ax = plt.subplot(nrows, ncols, k)
                plt.scatter(df[col_i], df[col_j])
                plt.xlabel(col_i)
                plt.ylabel(col_j)
                plt.title(f'{col_i} vs {col_j}')
                k += 1
        plt.tight_layout() # fit labels and ticks nicely together
        plt.show() # only called once, at the end of the function
    
    columns = ['speed', 'height', 'length', 'num_inversions']
    roller_coasters = pd.DataFrame(np.random.rand(20, len(columns)), columns=columns)
    scatter(roller_coasters, ['speed', 'height', 'length', 'num_inversions'])
    

    【讨论】:

    • 这行得通!谢谢!
    猜你喜欢
    • 2011-03-14
    • 2018-06-23
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多