简体   繁体   English

Python matplotlib 极坐标未按预期绘制

[英]Python matplotlib polar coordinate is not plotting as it is supposed to be

I am plotting from a CSV file that contains Cartesian coordinates and I want to change it to Polar coordinates, then plot using the Polar coordinates.我正在从包含笛卡尔坐标的 CSV 文件中绘制,我想将其更改为极坐标,然后使用极坐标将其更改为 plot。

Here is the code这是代码

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

df = pd.read_csv('test_for_plotting.csv',index_col = 0)

x_temp = df['x'].values
y_temp = df['y'].values

df['radius'] =  np.sqrt( np.power(x_temp,2) + np.power(y_temp,2) )
df['theta'] = np.arctan2(y_temp,x_temp)
df['degrees'] = np.degrees(df['theta'].values)
df['radians'] = np.radians(df['degrees'].values)

ax = plt.axes(polar = True)
ax.set_aspect('equal')
ax.axis("off")

sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white','figure.figsize':(10,10)})
# sns.scatterplot(data = df, x = 'x',y = 'y', s= 1,alpha = 0.1, color = 'black',ax = ax)
sns.scatterplot(data = df, x = 'radians',y = 'radius', s= 1,alpha = 0.1, color = 'black',ax = ax)

plt.tight_layout()
plt.show()

Here is the dataset这是数据集

If you run this command using polar = False and use this line to plot sns.scatterplot(data = df, x = 'x',y = 'y', s= 1,alpha = 0.1, color = 'black',ax = ax) it will result in this picture如果您使用polar = False运行此命令并将此行用于 plot sns.scatterplot(data = df, x = 'x',y = 'y', s= 1,alpha = 0.1, color = 'black',ax = ax)它会导致这张图片图片

now after setting polar = True and run this line to plot sns.scatterplot(data = df, x = 'radians',y = 'radius', s= 1,alpha = 0.1, color = 'black',ax = ax) It is supposed to give you this现在设置polar = True并将这条线运行到 plot sns.scatterplot(data = df, x = 'radians',y = 'radius', s= 1,alpha = 0.1, color = 'black',ax = ax)supposed给你这个阴谋

But it is not working as if you run the actual code the shape in the Polar format is the same as Cartesian which does not make sense and it does not match the picture I showed you for polar (If you are wondering where did I get the second picture from, I plotted it using R)但它不起作用,就像您运行实际代码一样,极坐标格式的形状与笛卡尔格式相同,这没有意义,并且与我向您展示的极坐标图片不匹配(如果您想知道我从哪里得到第二张图片,我用 R 绘制的)

I would appreciate your help and insights and thanks in advance!感谢您的帮助和见解,并在此先感谢!

For a polar plot, the "x-axis" represents the angle in radians.对于极坐标 plot,“x 轴”以弧度表示角度。 So, you need to switch x and y, and convert the angles to radians (I also added ax=ax , as the axes was created explicitly):因此,您需要切换 x 和 y,并将角度转换为弧度(我还添加了ax=ax ,因为轴是明确创建的):

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

data = {'radius': [0, 0.5, 1, 1.5, 2, 2.5], 'degrees': [0, 25, 75, 155, 245, 335]}

df_temp = pd.DataFrame(data)
ax = plt.axes(polar=True)
sns.scatterplot(x=np.radians(df_temp['degrees']), y=df_temp['radius'].to_numpy(),
                s=100, alpha=1, color='black', ax=ax)
for deg, y in zip(df_temp['degrees'], df_temp['radius']):
    x = np.radians(deg)
    ax.axvline(x, color='skyblue', ls=':')
    ax.text(x, y, f'  {deg}', color='crimson')
ax.set_rlabel_position(-15)  # Move radial labels away from plotted dots
plt.tight_layout()
plt.show()

极坐标散点图

About your new question: if you have an xy plot, and you convert these xy values to polar coordinates, and then plot these on a polar plot, you'll get again the same plot. About your new question: if you have an xy plot, and you convert these xy values to polar coordinates, and then plot these on a polar plot, you'll get again the same plot.

After some more testing with the data, I decided to create the plot directly with matplotlib, as seaborn makes some changes that don't have exactly equal effects across seaborn and matplotlib versions. After some more testing with the data, I decided to create the plot directly with matplotlib, as seaborn makes some changes that don't have exactly equal effects across seaborn and matplotlib versions.

What seems to be happening in R: R 中似乎发生了什么:

  • The angles (given by "x") are spread out to fill the range (0,2 pi).角度(由“x”给出)展开以填充范围(0,2 pi)。 This either requires a rescaling of x, or change how the x-values are mapped to angles.这要么需要重新缩放 x,要么更改 x 值映射到角度的方式。 One way to get this, is subtracting the minimum.一种方法是减去最小值。 And with that result divide by the new maximum and multiply by 2 pi.结果除以新的最大值并乘以 2 pi。
  • The 0 of the angles it at the top, and the angles go clockwise.顶部的角度为 0,顺时针方向的角度为 go。

The following code should create the plot with Python.以下代码应使用 Python 创建 plot。 You might want to experiment with alpha and with s in the scatter plot options.您可能想在分散 plot 选项中使用alphas进行试验。 (Default the scatter dots get an outline, which often isn't desired when working with very small dots, and can be removed by lw=0 .) (默认散点会得到一个轮廓,这在处理非常小的点时通常是不需要的,可以通过lw=0删除。)

ax = plt.axes(polar=True)
ax.set_aspect('equal')
ax.axis('off')
x_temp = df['x'].to_numpy()
y_temp = df['y'].to_numpy()
x_temp -= x_temp.min()
x_temp = x_temp / x_temp.max() * 2 * np.pi
ax.scatter(x=x_temp, y=y_temp, s=0.05, alpha=1, color='black', lw=0)
ax.set_rlim(y_temp.min(), y_temp.max())
ax.set_theta_zero_location("N")  # set zero at the north (top)
ax.set_theta_direction(-1) # go clockwise
plt.show()

At the left the resulting image, at the right using the y-values for coloring ( ax.scatter(..., c=y_temp, s=0.05, alpha=1, cmap='plasma_r', lw=0) ):在左侧生成图像,在右侧使用 y 值进行着色( ax.scatter(..., c=y_temp, s=0.05, alpha=1, cmap='plasma_r', lw=0) ):

类似于 R 图的极坐标图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM