我写这篇文章是为了在用散点图绘制圆时有一个参考帖子,但用户想要提供分散圆的真实半径,而不是抽象的大小.
我一直在四处寻找,还有其他帖子解释了它的原理,但还没有遇到现成的功能.我已经试过了,希望我已经接近找到解决方案.
这就是我到目前为止所拥有的:
import matplotlib.pyplot as plt
import numpy as np
def true_scatter(x, y, r, ax, **kwargs):
# Should work for an equal aspect axis
ax.set_aspect('equal')
# Access the DPI and figure size
dpi = ax.figure.dpi
fig_width_inch, _ = ax.figure.get_size_inches()
# Calculate plot size in data units
xlim = ax.get_xlim()
plot_width_data_units = xlim[1] - xlim[0]
# Calculate the scale factor: pixels per data unit
plot_width_pixels = fig_width_inch * dpi
scale = plot_width_pixels / plot_width_data_units
# Convert radius to pixels, then area to points squared
radius_pixels = r * scale
area_pixels_squared = np.pi * (radius_pixels ** 2)
area_points_squared = area_pixels_squared * (72 / dpi) ** 2
# Scatter plot with converted area
scatter = ax.scatter(x, y, s=area_points_squared, **kwargs)
return scatter
# Example with single scatter
fig, ax = plt.subplots()
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
scatter = true_scatter(0, 0, 1, ax)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
plt.grid()
plt.show()
不幸的是,这并不完全是答案.我得到一个半径为~1.55的圆,而不是1. 有没有人能发现我的方法有什么问题?
谢谢!