matplotlib中的散点图和组合极性直方图

2024-04-29 07:51:32 发布

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

我试图制作一个类似这样的图,它结合了笛卡尔散点图和极坐标直方图。(径向线可选) enter image description here 存在类似的解决方案(通过Nicolas Legrand)来查看x和y(code here)中的差异,但我们需要查看比率(即x/y)。 enter image description here

更具体地说,当我们想要查看相对风险度量时,这是有用的,相对风险度量是两个概率的比率

散点图本身显然不是问题,但极坐标直方图更先进

我发现的最有希望的线索是matplotlib图库here中的这个中心示例 enter image description here

我曾尝试过这样做,但却遇到了matplotlib技能的极限。为实现这一目标所作的任何努力都将是巨大的


Tags: here度量matplotlibcode差异解决方案直方图概率
3条回答

嗯。多亏了尼古拉斯的answer和托姆金的answer,我有了一个有效的解决方案:)

import numpy as np
import matplotlib.pyplot as plt

# Scatter data
n = 50
x = 0.3 + np.random.randn(n)*0.1
y = 0.4 + np.random.randn(n)*0.02

def radial_corner_plot(x, y, n_hist_bins=51):
    """Scatter plot with radial histogram of x/y ratios"""

    # Axis setup
    fig = plt.figure(figsize=(6,6))
    ax1 = fig.add_axes([0.1,0.1,.6,.6], label="cartesian")
    ax2 = fig.add_axes([0.1,0.1,.8,.8], projection="polar", label="polar")
    ax2.set_rorigin(-20)
    ax2.set_thetamax(90)

    # define useful constant
    offset_in_radians = np.pi/4

    def rotate_hist_axis(ax):
        """rotate so that 0 degrees is pointing up and right"""
        ax.set_theta_offset(offset_in_radians)
        ax.set_thetamin(-45)
        ax.set_thetamax(45)
        return ax

    # Convert scatter data to histogram data
    r = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    h, b = np.histogram(phi, 
                        bins=np.linspace(0, np.pi/2, n_hist_bins),
                        density=True)

    # SCATTER PLOT                            -
    ax1.scatter(x,y)

    ax1.set(xlim=[0, 1], ylim=[0, 1], xlabel="x", ylabel="y")
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)


    # HISTOGRAM                              
    ax2 = rotate_hist_axis(ax2)
    # rotation of axis requires rotation in bin positions
    b = b - offset_in_radians

    # plot the histogram
    bars = ax2.bar(b[:-1], h, width=b[1:] - b[:-1], align='edge')

    def update_hist_ticks(ax, desired_ratios):
        """Update tick positions and corresponding tick labels"""
        x = np.ones(len(desired_ratios))
        y = 1/desired_ratios
        phi = np.arctan2(y,x) - offset_in_radians
        # define ticklabels
        xticklabels = [str(round(float(label), 2)) for label in desired_ratios]
        # apply updates
        ax2.set(xticks=phi, xticklabels=xticklabels)
        return ax

    ax2 = update_hist_ticks(ax2, np.array([1/8, 1/4, 1/2, 1, 2, 4, 8]))

    # just have radial grid lines
    ax2.grid(which="major", axis="y")

    # remove bin count labels
    ax2.set_yticks([])

    return (fig, [ax1, ax2])

fig, ax = radial_corner_plot(x, y)

谢谢你的指点

enter image description here

我相信其他人会有更好的建议,但有一种方法可以得到你想要的东西(不需要额外的轴艺术家),那就是将极轴投影与散点图和条形图结合使用。差不多

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(size=100)
y = np.random.uniform(size=100)

r = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)

h, b = np.histogram(phi, bins=np.linspace(0, np.pi/2, 21), density=True)
colors = plt.cm.Spectral(h / h.max())

ax = plt.subplot(111, projection='polar')
ax.scatter(phi, r, marker='.')
ax.bar(b[:-1], h, width=b[1:] - b[:-1], 
       align='edge', bottom=np.max(r) + 0.2,  color=colors)
# Cut off at 90 degrees
ax.set_thetamax(90)
# Set the r grid to cover the scatter plot
ax.set_rgrids([0, 0.5, 1])
# Let's put a line at 1 assuming we want a ratio of some sort
ax.set_thetagrids([45], [1])

这将给 enter image description here

它缺少轴线标签和一些美化,但它可能是一个开始。我希望这是有帮助的

可以使用两个相互重叠的轴:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_axes([0.1,0.1,.8,.8], label="cartesian")
ax2 = fig.add_axes([0.1,0.1,.8,.8], projection="polar", label="polar")

ax2.set_rorigin(-1)
ax2.set_thetamax(90)
plt.show()

enter image description here

相关问题 更多 >