【问题标题】:matplotlib summary plot per record每条记录的 matplotlib 汇总图
【发布时间】:2013-07-01 14:42:47
【问题描述】:

我需要为数据库中的每条记录创建单个参数的摘要图。使用下面的代码,我设法为每条记录创建了一个子图(测试数据库中的 5 个,ArcGIS 10.0 文件地理数据库,Python 2.6.5,Matplotlib 1.0.0),但每个子图都是相同的。我在论坛中搜索了摘要图/报告、子图语法和循环技术的示例,试图确定正确的语法。我希望我的问题是不正确的循环语法,因为我正在绘制每个图的所有记录,而不是每个图所需的一条记录。在我解决了这个基本的绘图问题之后,我计划扩展我的代码范围,使每个绘图包含 10-15 个参数、总共 3-4 个绘图和一些一般摘要信息,所有这些都在每条记录的单页 pdf 上。我总共处理了几千条记录。

这是我在 Stack Overflow 上的第一篇文章。在过去的一年中,该论坛在许多场合对我来说都是非常有用的资源。我是 python 的新手,也是使用 matplotlib 的新手,但我看到了语言和这个库的巨大潜力。非常感谢任何帮助或建议!

import arcpy
import os
import matplotlib
import matplotlib.pyplot as plt

#Variables
FC = arcpy.GetParameterAsText(0) #feature class
P1_fld = arcpy.GetParameterAsText(1) #score field to chart
P2_fld = arcpy.GetParameterAsText(2) #score field to chart
plt.subplots_adjust(hspace=0.4)
nsubp = int(arcpy.GetCount_management(FC).getOutput(0)) #pulls n subplots from FC
last_val = object()

#Sub-plot loop
cur = arcpy.SearchCursor(FC, "", "", P1_fld)
for row in cur:
    x=1
    y=row.getValue(P1_fld)
    if row.OBJECTID != last_val:
        for i,v in enumerate(xrange(nsubp)):
            v = v+1
            i = i+1
            ax = plt.subplot(nsubp,1,v) # Create a subplot.
            ax.scatter(x,y,s=5,color='blue'); # Generate the Scatter Plot.
            oid = str(row.getValue('OBJECTID'))
            figPDf = r"filepath.pdf" # Save the Scatter Plot to PDF.
            plt.savefig(figPDf)
del row, cur
os.startfile("filepath.pdf")

【问题讨论】:

  • 结合 i,v in enumerate(xrange(nsubp)): with v=v+1 and i=i+1 似乎很麻烦
  • 发生这种情况是因为您使用了双 for 循环:您正在为每次迭代(即每个子图)绘制所有参数。

标签: matplotlib summary arcpy


【解决方案1】:

发生这种情况是因为您有两个嵌套的 for 循环:第一个循环遍历每个 row,而第二个循环使散点图出现在 每个 子图上。这反过来意味着每个绘制的参数都将出现在每个子图上。为避免这种情况,您应该避免双 for 循环。

我不确定我是否完全理解您想要实现的目标,但这至少应该能让您顺利上路。

import arcpy
import os
import matplotlib
import matplotlib.pyplot as plt

#Variables
FC = arcpy.GetParameterAsText(0) #feature class
P1_fld = arcpy.GetParameterAsText(1) #score field to chart
P2_fld = arcpy.GetParameterAsText(2) #score field to chart
plt.subplots_adjust(hspace=0.4)
nsubp = int(arcpy.GetCount_management(FC).getOutput(0)) #pulls n subplots from FC
last_val = object()

#Sub-plot loop
cur = arcpy.SearchCursor(FC, "", "", P1_fld)
i = 0
x = 1
for row in cur:
    y = row.getValue(P1_fld)
    if row.OBJECTID != last_val:
        i += 1
        ax = plt.subplot(nsubp, 1, i) # Create a subplot.
        ax.scatter(x, y, s=5, color='blue'); # Generate the Scatter Plot.
        oid = str(row.getValue('OBJECTID'))
        figPDf = r"filepath.pdf" # Save the Scatter Plot to PDF.
        plt.savefig(figPDf)
del row, cur
os.startfile("filepath.pdf")

【讨论】:

  • 你完全正确。我的双 for 循环导致了这个问题。当我删除第二个 for 循环并合并您的编辑时,5 个图只显示了一个记录的值。为了让每个记录值单独绘制,我还需要删除“if row.OBJECTID”语句并删除下面的所有内容。该脚本现在为每条记录提供了一个独特的情节,这正是我所需要的。非常感谢,nordev!
猜你喜欢
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 2021-02-16
  • 2022-01-20
  • 2017-03-18
  • 1970-01-01
  • 2018-01-09
  • 2011-03-15
相关资源
最近更新 更多