在散点图中绘制小极坐标图-Python

时间:2020-06-18 13:16:34

标签: python data-visualization data-science

我进行了编辑以使问题更具体。我有一个包含4个变量的数据集:'x','y','Length'和'Direction'。变量“方向”是极坐标。我被要求做一个散点图,然后将每个点变成一个反映其长度和方向的小极坐标图。我尝试使用颤振器制作矢量,但结果不理想。我将我的代码附加到散点图,示例数据框和显示我所需输出的png。scatterplot with each point changed into a small polar plot

bc = pd.DataFrame({'x':[2,4,6], 'y':[1,3,5], 'Length':[10,25,23], 'Direction':[-86,-85,-80]})   
plt.figure(figsize=(14, 7))
ax = sns.scatterplot(x="x", y="y", data=bc)
plt.title('Scatter Plot of x and y')

1 个答案:

答案 0 :(得分:3)

这是一种可能的方法。考虑到角度和长度,使用给定的x和y创建一个三角形。如果默认方向(指向右侧的零角度)不是所需的方向,则可以在正弦和/或余弦上添加减号。另外,可以互换正弦和余弦的作用以对角镜像角度。

为防止角度看起来变形,可以使用set_aspect('equal')

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

bc = pd.DataFrame({'x': [2, 4, 6], 'y': [1, 3, 5], 'Length': [10, 25, 23], 'Direction': [-86, -85, -80]})
plt.figure(figsize=(14, 7))

delta = 15  # half of the aperture angle (in degrees)
length_factor = 1 / bc['Length'].max()  # this makes the longest 1 unit long
for x, y, length, dir in zip(bc['x'], bc['y'], bc['Length'], bc['Direction']):
    for is_backgr in (True, False):
        if is_backgr:
            arc_angles = np.linspace(dir + delta, dir + 360 - delta, 32)
        else:
            arc_angles = np.linspace(dir - delta, dir + delta, 10)
        c_arr = np.cos(np.radians(arc_angles))
        s_arr = np.sin(np.radians(arc_angles))
        r = length * length_factor
        x_arr = x + np.pad(c_arr * r, (1, 1))
        y_arr = y + np.pad(s_arr * r, (1, 1))
        plt.fill(x_arr, y_arr, c='grey' if is_backgr else 'crimson', alpha=0.2)
        plt.plot(x_arr, y_arr, c='black' if is_backgr else 'crimson', lw=0.5 if is_backgr else 2)
ax = sns.scatterplot(x="x", y="y", data=bc, s=100)
ax.set_title('Scatter Plot of x and y')
ax.set_aspect('equal')
plt.show()

example plot