用python进行数据转换

2024-07-02 12:35:44 发布

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

我有一个对数缩放的数据集,我想转换数据以测量每个组中数据集的密度。 我用虚线做了一个散点图。它的唯一目的是可视化数据

enter image description here

我需要像这样的转变

enter image description here

你有没有办法,我该如何旋转数据

以下是有关数据的一个小示例:

import matplotlib.pyplot as plt

x = [0.80212184, 2.47838352, 1.04379475, 1.42871703, 2.34573573,
       1.80048663, 1.51099012, 2.47128927, 1.89730346, 1.6375945 ,
       0.77876967, 0.76479765, 0.30721789, 2.90775006, 2.91452946]
y= [7.568806  , 6.63653933, 7.57696614, 8.471096  , 8.75421651,
       8.55456059, 8.1826057 , 8.62866297, 8.45774376, 8.26221853,
       7.84199122, 7.60613018, 8.31732613, 7.09044142, 7.08366203]
df = pd.DataFrame(np.array([x,y]).T, columns= ['x','y'])
supportlineY = [8.5,6.5]
supportline1X = [0,1.7]
supportline2X = [0.5,2.2]
supportline3X = [1,2.7]
supportline4X = [1.5,3.2]
supportline5X = [2,3.7]

plt.scatter(df['x'],df['y'])
plt.plot(supportline1X,supportlineY)
plt.plot(supportline2X,supportlineY)
plt.plot(supportline3X,supportlineY)
plt.plot(supportline4X,supportlineY)
plt.plot(supportline5X,supportlineY)

Tags: 数据目的dfplot可视化对数plt密度
1条回答
网友
1楼 · 发布于 2024-07-02 12:35:44

可以将坐标乘以旋转矩阵:

# sample dataframe
df = pd.DataFrame({
    'x': np.arange(100),
    'y': np.arange(100) + np.random.randint(-10, 10, 100)})

# rotation angle, degrees
theta_deg = -45
theta = theta_deg / 180 * np.pi

# rotation matrix
rot = np.array([
    [np.cos(theta), -np.sin(theta)],
    [np.sin(theta), np.cos(theta)]
])

# rotated data
df_rot = pd.DataFrame(
    df[['x', 'y']].values.dot(rot),  # A * rot
    columns=['x', 'y'])

# plot
fig, ax = plt.subplots()
df.plot.scatter('x', 'y', color='green', ax=ax)
df_rot.plot.scatter('x', 'y', color='red', ax=ax)

输出:

chart

当然,您需要为您的数据找到正确的theta_deg角度,但是由于您已经有了支持行,我认为这不是问题

相关问题 更多 >