How to create a polar density plot having a list of angles values in degrees in (.txt) file

Viewed 149

I am trying to produce a density plot in polar coordinates if I have a list of angles amplitudes in degrees in a dihedrals.txt file: for example: 359.262 13.174 352.603 334.395 351.922 8.914 354.485 340.591 15.376 351.65 21.108 338.342 9.592 359.583 13.285 354.237 22.613 6.483 0.542 336.274 12.243 12.563 346.091

I have read some of the answers here but so far I have not found anything that works for what I want. This is an example of the code I have tried to use:

    # Import environmental variables from bash script
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.stats import gaussian_kde
from matplotlib.colors import Normalize 
from scipy.interpolate import interpn
import math

second_count=8
Tt = 1

angles = np.loadtxt('dihedrals.txt')

sin_angles = np.sin(angles)

cos_angles = np.cos(angles)

xy = np.vstack([sin_angles, cos_angles])

z = gaussian_kde(xy)(xy)

# Compute areas and colors

r = 2 * angles
theta = 2 * np.pi * angles
area = 10 * r**2
colors = theta


fig = plt.figure()
ax1 = fig.add_subplot(projection='polar')
ax1.scatter(sin_angles, cos_angles, c=z, alpha = 0.75)

plt.show()
1 Answers

Here is one approach, which is heavily inspired by this answer.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

np.random.seed(0)
# get fake data for angles, measured in radians
angles = 2 * np.pi * np.random.rand(100) ** 2
# and radii in [0, 1]
radii = np.random.rand(100)

# Interpolation step:
N = 500 # number of points used to evaluate the interpolation
interp = gaussian_kde(np.vstack((angles, radii)))
# define ranges for interpolation
angles_ = np.linspace(0, 2 * np.pi, N)
radii_ = np.linspace(0, 1, N)

# to compute colors, first get the meshgrid of angles and radii
# with shape N x N x 2
mesh = np.stack(np.meshgrid(angles_, radii_), 0)
# then, compute N x N matrix of colors using `interp`
# I think we need to reshape to accomodate Gaussian KDE API, but maybe this can
# be avoided
colors = interp(mesh.reshape(2, -1)).reshape(N, N)

fig = plt.figure()
ax1 = fig.add_subplot(projection='polar')
ax1.contourf(angles_, radii_, colors, alpha = 0.75)

plt.show()

Resulting in:

Example of interpolation in polar coordinates

Note that the interpolation used here does not respect periodic boundary conditions.

Related