Matplotlib中的散点图和极坐标直方图组合

4
我尝试制作一个类似于此图的图表,它将笛卡尔散点图和极坐标直方图结合起来。(径向线是可选的) enter image description here 类似的解决方案(由Nicolas Legrand提供)用于查看x和y的差异(代码在这里),但我们需要查看比率(即x/y)。 enter image description here 更具体地说,当我们想要查看两个概率的比值时,这非常有用。
单独的散点图显然不是问题,但极坐标直方图更为高级。
我找到的最有前途的线索是来自matplotlib画廊的这个中心示例在这里 enter image description here
我已经尝试过了,但是遇到了我的matplotlib技能的限制。任何朝着这个目标努力的尝试都将是伟大的。
3个回答

4

我相信其他人会有更好的建议,但一个能够得到 类似于 您想要的东西(无需额外的轴艺术家)的方法是将极坐标投影与散点图和条形图结合使用。就像这样:

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

尽管它缺少坐标轴标签和一些美化处理,但这可能是一个起点。希望这对你有所帮助。


2

您可以在彼此之上使用两个轴:

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


1

好的。感谢Nicolas提供的答案和tomjn提供的答案,我现在有了可行的解决方案 :)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接