POST
|
Using Python, how do I set or unset "show values out of range" for a legend? ArcGIS Pro 2.4
... View more
11-23-2019
02:11 PM
|
2
|
0
|
340
|
POST
|
I figured it out. The error I was making is that the GEOID field type in the counties shapefile is Text, whereas it is Integer in the CSV file. I added a new field to the counties table and calculated the value (float) of the GEOID for each row, then did the join on this new GEOID.
... View more
11-19-2019
05:43 AM
|
3
|
0
|
587
|
POST
|
I have been struggling with Joins on ArcGis Pro. After some unexpected and undesired results using Spatial Join, I tried what I thought would be a simple join using public data. Unfortunately, the result shows zeros for rows where I know there is data. I used Excel to calculate the population and households for US counties, the results of which are in the attached CSV file. This file has the same GEOID values as the cb_2017_us_county_5m shapefile from the census.gov site (https://www2.census.gov/geo/tiger/GENZ2017/shp/cb_2017_us_county_5m.zip). I used the Join Field data management tool with the following paramters: Join Field Parameters: Input Table: cb_2017_us_county_5m Input Join Field: GEOID Join Table: county_pops_hh-2017a.csv Output Join Field: GEOID Join Fields: Pops2017;Households2017 Updated Input Table: cb_2017_us_county_5m The results show zeros for population and households for counties in Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, which is not correct. The data in the Join Table is sorted alphabetically by county FP, then by state. This brings into question the validity of reports I have generated using Joins in the past. Am I doing something wrong or is this a known issue? ArcGIS Pro 2.3.0 Windows 10 Enterprise
... View more
11-18-2019
09:03 AM
|
0
|
1
|
656
|
POST
|
I have a Python script that creates maps that are used for periodic reports. A requirement is that the scale in the legends be consistent for all reports created. This is not an issue, I override the break definition in the script. The problem is that if the value for a given polygon exceeds the upper range of the scale, that polygon is not displayed. Not only do I want that polygon shown, but I want it to be bright red to show visually that the threshold has been exceeded. Is there a way to have a top-most category in the legend to capture any value greater than the upper most threshold, i.e. greater than largest upperBound?
... View more
02-12-2019
12:36 PM
|
1
|
0
|
203
|
POST
|
I am trying to understand what is possible with Annotation layers. The Convert Labels To Annotation tool will save an annotation layer to the output geodatabase of choice. Is it possible to retrieve the saved annotation definition to apply it to a new map layer? Edit: I now understand that the Annotation layer can be exported to a layer and saved to disk. My motivation was to be able to automate consistent labeling between datasets as they are updated. An annotation layer can be used to provide labels for elements that don't change, like geographical names.
... View more
02-06-2019
08:30 AM
|
0
|
0
|
255
|
POST
|
How can I set the Language for a Label Class from Python? The code below works only if the language has been manually set to Python. I would like to be able to set the language from within the code. Edit: Asked a different way, is there a way to determine what the current setting is for Language in the Label Class? With this information, the returned expression format can match the current Language setting. aprx = arcpy.mp.ArcGISProject('CURRENT')
m = aprx.listMaps()[0]
lyr = m.listLayers()[0]
if lyr.supports('SHOWLABELS'):
lyr.listLabelClasses()[0].expression = '\'<FNT name="Arial" size="8">\' + str([targetMap_STATEFP]) + \'</FNT>\''
lyr.listLabelClasses()[0].visible = True
m.listLayers()[0].showLabels = True
... View more
02-05-2019
01:25 PM
|
0
|
3
|
914
|
POST
|
OK, I figured it out. Selecting the Manual Interval classification does not do anything. I suppose you can read it, but you cannot set it. So, per the documentation, to manually set class breaks, you must start with one of the standard classifications and make adjustments as needed. In the code below, I set the classification method to equal interval and set the number of desired breaks. I then overwrite each of the breaks. aprx = arcpy.mp.ArcGISProject('CURRENT')
workingLayer = aprx.listMaps()[0].listLayers()[0]
fieldName = 'Shape_Area'
sym = workingLayer.symbology
sym.updateRenderer('GraduatedColorsRenderer')
sym.renderer.colorRamp = aprx.listColorRamps('Bathymetric Scale')[0]
sym.renderer.classificationMethod = 'EqualInterval'
sym.renderer.classificationField = fieldName
sym.renderer.breakCount = 10
y = 0.3
x = y/10.0
for brk in sym.renderer.classBreaks:
print(str(i) + ': ' + str(x))
brk.upperBound = x
brk.label = '\u2264' + str(round(x,3))
x = round(x + (y/10),3)
workingLayer.symbology = sym
... View more
01-31-2019
06:32 AM
|
2
|
0
|
469
|
POST
|
Hello, I am unable to set the BreakCount for 'ManualInterval' symbology. The value remains zero. What is the proper way to set the number of breaks? It works for 'NaturalBreaks' classificationMethod but not for 'ManualInterval'. Changing the classification method in the code below and removing the references to classBreaks will work as expected. #ArcGIS Pro 2.1.2
#Python 3.6.2, 64 bit
aprx = arcpy.mp.ArcGISProject('CURRENT')
cwd = 'c:\\temp'
workingLayer = aprx.listMaps()[0].listLayers()[0]
sourceTable = arcpy.ListTables()[0]
sourceLayout = aprx.listLayouts()[0]
metric = ('Calc01Perc',(-0.5,0.5)) # (Field name, (min,max values))
sym = workingLayer.symbology
sym.updateRenderer('GraduatedColorsRenderer')
sym.renderer.classificationMethod = 'ManualInterval'
sym.renderer.classificationField = sourceTable + '_' + metric[0]
print('DEBUG fieldname: ' + sym.renderer.classificationField)
sym.renderer.colorRamp = aprx.listColorRamps('Bathymetric Scale')[0]
sym.renderer.breakCount = 10 # This does not stick for 'ManualInterval' or unspecified classificationMethod
print('DEBUG breakCount: ' + str(sym.renderer.breakCount) + '= 10 ?')
step = 0.1
breakVal = -0.5
print('DEBUG len(classBreaks) = ' + str(len(sym.renderer.classBreaks)))
for brk in sym.renderer.classBreaks:
brk.upperBound = breakVal
breakVal += step
print('DEBUG next break: ' + str(breakVal))
workingLayer.symbology = sym
... View more
01-30-2019
09:23 AM
|
0
|
1
|
659
|
POST
|
Lance, Thanks for all your help. I had to make a couple tweaks to your code to finally get it working. For some reason, setting the datatype to DEFile in the parameter definition for the CSV file did not work, but DETable did. Using DEFile would not allow table to table conversion. Also, I hadn't realized that the Shapefile was opened as a feature class, which cannot be joined with a table. So I made a feature layer to add the join. Again, I am very grateful for your help. I learned a lot while going through this exercise. Here is the working code: import arcpy, os
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = 'actionPuree'
self.alias = 'actionPureeToolBox'
# List of tool classes associated with this toolbox
self.tools = [grindMixPuree]
class grindMixPuree(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = 'grindMixPuree'
self.description = 'Slices, dices, juliannes ' + \
'purees during the matinee ' + \
'and ready to serve'
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
parameters = []
# Reference States layer
baseStatesLayer = arcpy.Parameter(
displayName="Base States Layer",
name="baseStatesLayer",
#datatype="GPFeatureLayer",
datatype="DEShapefile",
parameterType="Required",
direction="Input")
parameters.append(baseStatesLayer)
# Data dump CSV file
inputDataDumpFile = arcpy.Parameter(
displayName="Data Dump File",
name="inputDataDumpFile",
datatype="DETable",
#datatype="DEFile",
parameterType="Required",
direction="Input")
parameters.append(inputDataDumpFile)
# Target Layer
targetMap = arcpy.Parameter(
displayName="output map",
name="targetMap",
#datatype="DEMapDocument",
datatype="GPFeatureLayer",
parameterType="Derived",
direction="Output")
#targetMap.parameterDependencies = [baseStatesLayer.name]
targetMap.schema.clone = True #
parameters.append(targetMap)
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
# parameters[0] = US States shapefile from census.gov
# parameters[1] = CSV file with one record for each US state or territory
# parameters[2] = Copy of parameters[0] for editing
sourceShp = parameters[0].valueAsText
sourceCSV = parameters[1].valueAsText
outputFeatureClass = parameters[2].name
arcpy.CopyFeatures_management(sourceShp,outputFeatureClass)
# Get and set current project and geodatabase info
arcpy.env.overwriteOutput = True
aprx = arcpy.mp.ArcGISProject('CURRENT')
defaultGeoDb = arcpy.env.workspace
aprx.defaultGeodatabase = defaultGeoDb
cwd = os.path.dirname(os.path.realpath(sourceCSV))
currentMap = aprx.listMaps()[0]
#Create target names based on name of input table
tempStr = os.path.splitext(os.path.basename(parameters[1].valueAsText))[0]
#remove any special characters - ArcGis does not like dashes
cmpCharList = ['-','+','=','*','?','&','!','#',' ','/','_']
for ch in cmpCharList:
tempStr = tempStr.replace(ch, '')
newMapName = 'map_' + tempStr[-9:]
newTableName = 'tbl_' + tempStr[-9:]
#Convert the CSV file to a table - the new table should be in the geodatabase
arcpy.TableToTable_conversion(sourceCSV,defaultGeoDb,newTableName)
#Add fields to the newly converted table
arcpy.AddField_management(newTableName,'Calc01Perc','DOUBLE')
arcpy.AddField_management(newTableName,'Calc02','DOUBLE')
#Join table with shapefile ... cannot join a feature class - must first create a feature layer
tempLayer = 'outputFeatureLayer'
arcpy.MakeFeatureLayer_management (outputFeatureClass, tempLayer)
newJoinLayer = arcpy.AddJoin_management(tempLayer, 'STUSPS', newTableName, 'Abbr', 'KEEP_ALL')
# Copy the shapefile with join to a new permanent feature class in GDB - join will not be needed after
arcpy.CopyFeatures_management(newJoinLayer, newMapName)
# Add new feature class to Map - full path need to FC in database
currentMap.addDataFromPath(os.path.join(defaultGeoDb, newMapName))
return
... View more
01-29-2019
05:07 AM
|
0
|
0
|
3285
|
POST
|
Cheers! I made the change, alas I get the same error with the addTable command on line 97. I suspect I do not have the correct understanding of the Table to Table conversion on line 90. Is it creating a table that I can open and manipulate (add fields, calculations), and later join with a shapefile? I added the CSV extension to the new table name on this round to see what would happen. It didn't change anything either way. import arcpy, os
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = 'actionPuree'
self.alias = 'actionPureeToolBox'
# List of tool classes associated with this toolbox
self.tools = [grindMixPuree]
class grindMixPuree(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = 'grindMixPuree'
self.description = 'Slices, dices, juliannes ' + \
'purees during the matinee ' + \
'and ready to serve'
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
parameters = []
# Reference States layer
baseStatesLayer = arcpy.Parameter(
displayName="Base States Layer",
name="baseStatesLayer",
# datatype="DEShapefile",
datatype="GPFeatureLayer",
#datatype="GPLayer",
parameterType="Required",
direction="Input")
parameters.append(baseStatesLayer)
# Data dump CSV file
inputDataDumpFile = arcpy.Parameter(
displayName="Data Dump File",
name="inputDataDumpFile",
datatype="DETable",
parameterType="Required",
direction="Input")
parameters.append(inputDataDumpFile)
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
# parameters[0] = US States shapefile from census.gov
# parameters[1] = CSV file with one record for each US state or territory
# Get and set current project and geodatabase info
arcpy.env.overwriteOutput = True
aprx = arcpy.mp.ArcGISProject('CURRENT')
defaultGeoDb = arcpy.env.workspace
aprx.defaultGeodatabase = defaultGeoDb
cwd = os.path.dirname(os.path.realpath(parameters[1].valueAsText))
#Create target names based on name of input table (there is probably a more pythonic way to do this)
tempStr = (repr(parameters[1].valueAsText).split('\\')[-1]).rstrip('\'')
tempList = tempStr.split('.')
if len(tempList)>1:
tempStr = ''
for i in range(len(tempList)-1):
tempStr = tempStr + tempList[i]
else:
tempStr = tempList[0]
newMapName= 'lyr_' + tempStr
newTableName = 'tbl_' + tempStr + '.csv'
#Convert the CSV file to a table
arcpy.TableToTable_conversion(parameters[1].valueAsText,cwd,newTableName)
#Add fields to the newly converted table
arcpy.AddField_management(newTableName,'Calc01Perc','DOUBLE')
arcpy.AddField_management(newTableName,'Calc02','DOUBLE')
#Add table to the current project
currentMap = aprx.listMaps()[0]
# currentMap.addTable(newTableName) # ValueError: tbl_us_state_vegetables.csv
#Join table with shapefile
newJoinLayer = arcpy.management.AddJoin(parameters[0].valueAsText, 'STUSPS', newTableName, 'Abbr', 'KEEP_ALL')
# Copy the layer to a new permanent feature class
arcpy.CopyFeatures_management(newJoinLayer, newMapName)
arcpy.MakeTableView_management(newMapName, str(newMapName + '_tblView')) # where is the new table?
# currentMap.addLayer(newJoinLayer,'TOP') # FAIL: ValueError: tl_2018_us_state
# DEBUG: Show list of layers and tables
for currentMap in aprx.listMaps():
arcpy.AddMessage('Map Name: ' + currentMap.name)
for l in currentMap.listLayers():
arcpy.AddMessage(' Lyr: ' + l.name)
for t in currentMap.listTables():
arcpy.AddMessage(' Tbl: ' + t.name)
return
... View more
01-28-2019
08:29 AM
|
0
|
3
|
3285
|
POST
|
Here is the code, a little clean-up. import arcpy, os
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = 'actionPuree'
self.alias = 'actionPureeToolBox'
# List of tool classes associated with this toolbox
self.tools = [grindMixPuree]
class grindMixPuree(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = 'grindMixPuree'
self.description = 'Slices, dices, juliannes ' + \
'purees during the matinee ' + \
'and ready to serve'
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
parameters = []
# Reference States layer
baseStatesLayer = arcpy.Parameter(
displayName="Base States Layer",
name="baseStatesLayer",
# datatype="DEShapefile",
datatype="GPFeatureLayer",
#datatype="GPLayer",
parameterType="Required",
direction="Input")
parameters.append(baseStatesLayer)
# Data dump CSV file
inputDataDumpFile = arcpy.Parameter(
displayName="Data Dump File",
name="inputDataDumpFile",
datatype="DETable",
parameterType="Required",
direction="Input")
parameters.append(inputDataDumpFile)
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
# parameters[0] = US States shapefile from census.gov
# parameters[1] = CSV file with one record for each US state or territory
# Get and set current project and geodatabase info
arcpy.env.overwriteOutput = True
aprx = arcpy.mp.ArcGISProject('CURRENT')
defaultGeoDb = arcpy.env.workspace
aprx.defaultGeodatabase = defaultGeoDb
#Create target names based on name of input table (there is probably a more pythonic way to do this)
tempStr = (repr(parameters[1].valueAsText).split('\\')[-1]).rstrip('\'')
tempList = tempStr.split('.')
if len(tempList)>1:
tempStr = ''
for i in range(len(tempList)-1):
tempStr = tempStr + tempList[i]
else:
tempStr = tempList[0]
newMapName= 'lyr_' + tempStr
newTableName = 'tbl_' + tempStr
#Convert the CSV file to a table
arcpy.TableToTable_conversion(parameters[1].valueAsText,defaultGeoDb,newTableName)
#Add fields to the newly converted table
arcpy.AddField_management(newTableName,'Calc01Perc','DOUBLE')
arcpy.AddField_management(newTableName,'Calc02','DOUBLE')
#Add table to the current project
# currentMap.addTable(newTableName) # FAIL: SystemError: <built-in method addTable of MappingMapObject object at 0x00000000349AA9F0> returned a result with an error set
#Join table with shapefile
newJoinLayer = arcpy.management.AddJoin(parameters[0].valueAsText, 'STUSPS', newTableName, 'Abbr', 'KEEP_ALL')
# Copy the layer to a new permanent feature class
arcpy.CopyFeatures_management(newJoinLayer, newMapName)
arcpy.MakeTableView_management(newMapName, str(newMapName + '_tblView')) # where is the new table?
currentMap = aprx.listMaps()[0]
# currentMap.addLayer(newJoinLayer,'TOP') # FAIL: ValueError: tl_2018_us_state
# DEBUG: Show list of layers and tables
for currentMap in aprx.listMaps():
arcpy.AddMessage('Map Name: ' + currentMap.name)
for l in currentMap.listLayers():
arcpy.AddMessage(' Lyr: ' + l.name)
for t in currentMap.listTables():
arcpy.AddMessage(' Tbl: ' + t.name)
return
... View more
01-28-2019
06:46 AM
|
0
|
5
|
3285
|
POST
|
Lance, Thanks for the feedback. I agree the code I uploaded was unnecessarily sloppy. I will upload a clean-up version. I am not having much luck with the ModelBuilder but will continue toiling away. Thanks
... View more
01-28-2019
06:39 AM
|
0
|
0
|
3285
|
POST
|
Hello, How do you import a csv file, add fields to it, and join it with a shapefile? Attached is the failing code I've got so far. I can successfully join the table and the shapefile manually through the GUI, so the datafiles are good. However, i am unable to recreated this with a Toolbox script. I have been unable import the table, much less add fields and join it with a shapefile. I'm new to ArcGIS. I have found some code snippets, but nothing that seems to work. Thanks
... View more
01-27-2019
07:46 AM
|
0
|
8
|
4945
|
Title | Kudos | Posted |
---|---|---|
1 | 02-12-2019 12:36 PM | |
2 | 11-23-2019 02:11 PM | |
3 | 11-19-2019 05:43 AM | |
2 | 01-31-2019 06:32 AM |
Online Status |
Offline
|
Date Last Visited |
05-13-2021
11:32 AM
|