在散点图中绘制小的极坐标图

2024-05-29 06:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我编辑了一个数据集,它有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')

Tags: 数据代码编辑示例dataframepng矢量plt
1条回答
网友
1楼 · 发布于 2024-05-29 06:22:56

这是一种可能的方法。使用给定的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

相关问题 更多 >

    热门问题