-1

I have a shapefile with polygons and want to rotate each of them randomly. Centroid of the polygon should be the anchor point of rotation.

Rotation example:

enter image description here

closed as off-topic by Vince, PolyGeo Oct 24 '16 at 11:08

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking help to debug/write/improve code must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Providing a clear problem statement and evidence of a code attempt will help others to help you. See: How to create a Minimal, Complete, and Verifiable example." – Vince, PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.

1

This script will make a copy of your shapefile and randomly rotate every polygon:

# -*- coding: utf-8 -*-
import math
import arcpy
import numpy

def Transform_coords(x, y, angle, polygon_centroid):
    radians =  math.radians(angle)
    (X,Y) = polygon_centroid

    x_trans = x - X
    y_trans = y - Y

    x_transprime = math.cos(radians) * x_trans - math.sin(radians) * y_trans
    y_transprime = math.sin(radians) * x_trans + math.cos(radians) * y_trans

    x_prime = x_transprime + X
    y_prime = y_transprime + Y

    return x_prime, y_prime

def main(shp_file, new_shp_file):
    arcpy.env.overwriteOutput = True

    arcpy.MakeFeatureLayer_management (shp_file, "polygon")
    sr = arcpy.Describe("polygon").spatialReference
    features = []

    with arcpy.da.SearchCursor("polygon", ["SHAPE@", "SHAPE@XY"]) as cursor:
        for row in cursor:

            array = numpy.random.uniform(0, 360, size = 1)
            angle = array.tolist()[0]

            for feature_parts in row[0]:
                feature = []

                polygon_centroid = row[1]

                for coord in feature_parts: 
                    x = coord.X
                    y = coord.Y

                    new_x, new_y = Transform_coords(x, y, angle, polygon_centroid)
                    feature.append([new_x, new_y])

            points = arcpy.Array([arcpy.Point(*coords) for coords in feature])
            polygon_feature = arcpy.Polygon(points,sr)
            features.append(polygon_feature)

    arcpy.CopyFeatures_management(features, new_shp_file)

if __name__ == "__main__":
    main(
        shp_file = r"G:\Scripts\py_test\Misc\Arcpy_rotate_polygon_DEL\New_Shapefile.shp",
        new_shp_file = r"G:\Scripts\py_test\Misc\Arcpy_rotate_polygon_DEL\TEST.shp"
        )
  • 1
    Trigonometry functions are very expensive, and therefore should not be executed for each vertex. You could also save time by generating batches of random values in range 0...2pi. – Vince Oct 24 '16 at 10:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.