【问题标题】:Matplotlib patch not getting applied properlyMatplotlib 补丁未正确应用
【发布时间】:2021-12-01 16:26:51
【问题描述】:

我希望将上面的内容应用于我的散点图。但是我收到了这个

代码如下

# Data
import matplotlib.patches as patches
df1=pd.DataFrame({'x_pos': x, 'y_pos': y })
print(df1)

 
# Plot
fig1 = plt.figure(figsize=(20,10))
ax1 = fig1.add_subplot(111)
ax1.plot( 'x_pos', 'y_pos', data=df1, linestyle='none', marker='o')

 
# Annotation
ax1.add_patch(
patches.Circle(
(35, 40),          
3,                
alpha=0.3, facecolor="green", edgecolor="black", linewidth=1, linestyle='solid'
)
)

# Show the graph
plt.show()

数据框

   x_pos  y_pos
0       38  62506
3       33  64991
4       32  50825
5       44  57568
7       38  59365
..     ...    ...
301     44  55140
302     38  58062
303     48  59728
307     39  48513
310     43  45046

我在这里做错了什么?

【问题讨论】:

  • 您正在创建一个中心为(35, 40) 的圆,而数据点距离很远,x 值约为 40,y 值约为 60,000。另请注意,当 x 和 y 方向的纵横比存在较大差异时,圆会被挤压成细椭圆。
  • 我该如何解决这个问题? @JohanC​​pan>
  • 也许使用另一个中心?也许画一个 y 半径较大的椭圆?你想展示什么?
  • 我想用补丁突出显示图表的中间部分

标签: python matplotlib charts


【解决方案1】:

您可以使用 x 和 y 位置的平均值作为ellipse 的中心。以及它在两个方向上的半径在 x 和 y 中的标准偏差。请注意,对于椭圆,参数是宽度和高度,因此是半径的两倍。

from matplotlib import pyplot as plt
from matplotlib import patches
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'x_pos': np.random.randint(32, 49, 100),
                    'y_pos': np.random.randint(45000, 63000, 100)})
fig1 = plt.figure(figsize=(20, 10))
ax1 = fig1.add_subplot(111)
ax1.plot('x_pos', 'y_pos', data=df1, linestyle='none', marker='o')

ax1.add_patch(
    patches.Ellipse(
        (df1['x_pos'].mean(), df1['y_pos'].mean()),
        df1['x_pos'].std() * 2, df1['y_pos'].std() * 2,
        alpha=0.3, facecolor="green", edgecolor="black", linewidth=1, linestyle='solid'))

plt.show()

另请参阅this tutorial examplethis post,了解如何绘制置信椭圆。

下面是代码为 1,2 和 3 标准差绘制置信椭圆的样子(使用旋转数据测试椭圆旋转):

from matplotlib import pyplot as plt
from matplotlib import patches
import pandas as pd
import numpy as np

x = np.random.randint(32, 49, 100)
y = np.random.randint(45000, 50000, 100) + x * 500
df1 = pd.DataFrame({'x_pos': x, 'y_pos': y})

lamda, v = np.linalg.eig(np.cov(df1['x_pos'], df1['y_pos']))
lamda = np.sqrt(lamda)

fig1 = plt.figure(figsize=(20, 10))
ax1 = fig1.add_subplot(111)
ax1.plot('x_pos', 'y_pos', data=df1, linestyle='none', marker='o')

for num_std in range(1, 4):
    ax1.add_patch(
        patches.Ellipse(
            xy=(df1['x_pos'].mean(), df1['y_pos'].mean()),
            angle=np.rad2deg(np.arctan2(*v[:, 0][::-1])),
            width=lamda[0] * num_std * 2, height=lamda[1] * num_std * 2,
            alpha=0.1, facecolor="green", edgecolor="black", linewidth=1, linestyle='solid'))
plt.show()

【讨论】:

  • 这能回答你的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2019-02-20
  • 2020-12-11
  • 1970-01-01
  • 2018-04-24
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多