【问题标题】:Python - Stacking two histograms with a scatter plotPython - 用散点图堆叠两个直方图
【发布时间】:2017-02-05 09:52:26
【问题描述】:

有一个散点图的示例代码及其直方图

x = np.random.rand(5000,1)
y = np.random.rand(5000,1)



fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.scatter(x, y, facecolors='none')
ax.set_xlim(0,1)
ax.set_ylim(0,1)



fig1 = plt.figure(figsize=(7,7))
ax1 = fig1.add_subplot(111)
ax1.hist(x, bins=25, fill = None, facecolor='none', 
        edgecolor='black', linewidth = 1)



fig2 = plt.figure(figsize=(7,7))
ax2 = fig2.add_subplot(111)
ax2.hist(y, bins=25 , fill = None, facecolor='none', 
        edgecolor='black', linewidth = 1)

我想要做的是创建这个图表,直方图附在他们尊重的轴上,就像这个例子一样

我熟悉 x 轴的堆叠和合并

f, (ax1, ax2, ax3) = plt.subplots(3)
ax1.scatter(x, y)
ax2.hist(x, bins=25, fill = None, facecolor='none', 
        edgecolor='black', linewidth = 1)
ax3.hist(y, bins=25 , fill = None, facecolor='none', 
        edgecolor='black', linewidth = 1)

f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

但我不知道如何将直方图附加到 y 轴和 x 轴上,就像我在上面发布的图片中一样,最重要的是,如何改变图形的大小(即使散点图更大并且相比之下,直方图更小)

【问题讨论】:

    标签: python numpy matplotlib plot


    【解决方案1】:

    Seaborn 是快速统计图的最佳选择。但是如果你想避免其他依赖,你可以使用subplot2grid 放置子图和关键字sharexsharey 以确保轴同步。

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.random.randn(100)
    y = np.random.randn(100)
    
    scatter_axes = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)
    x_hist_axes = plt.subplot2grid((3, 3), (0, 0), colspan=2,
                                   sharex=scatter_axes)
    y_hist_axes = plt.subplot2grid((3, 3), (1, 2), rowspan=2,
                                   sharey=scatter_axes)
    
    scatter_axes.plot(x, y, '.')
    x_hist_axes.hist(x)
    y_hist_axes.hist(y, orientation='horizontal')
    

    在询问如何绘制某些内容之前,您应该始终查看matplotlib gallery,它可能会为您节省一些击键 - 我的意思是您不必问。画廊里实际上有两个这样的地块。不幸的是,代码很旧,没有利用subplot2gridthe first one 使用矩形,second one 使用axes_grid,这有点奇怪。这就是我发布此答案的原因。

    【讨论】:

      【解决方案2】:

      我认为仅使用matplotlib 很难做到这一点,但您可以使用具有jointplot 功能的seaborn

      import numpy as np
      import pandas as pd
      import seaborn as sns
      sns.set(color_codes=True)
      
      x = np.random.rand(1000,1)
      y = np.random.rand(1000,1)
      data = np.column_stack((x,y))
      df = pd.DataFrame(data, columns=["x", "y"])
      
      sns.jointplot(x="x", y="y", data=df);
      

      【讨论】: