【问题标题】:Subplot several scatter histograms子图几个散点直方图
【发布时间】:2019-12-27 22:52:23
【问题描述】:

有人可以分享一个示例来创建 4 个散点历史图作为子图吗? 澄清。我打算创建一个 pdf 的情节。每个页面将有 4 个子图。每个子图都是散点直方图。

创建散点直方图的例子好像是this

与使用此散点图示例并绘制每个子图相比,是否有任何替代函数可以在更少的行中执行此操作?

【问题讨论】:

  • 您面临的具体问题是什么?你能创建 4 个子图吗? (fig, axs = plt.subplots(2,2)) 然后对axs中的四个轴中的每一个使用示例?
  • 对不够清晰深表歉意。我想知道是否有比将示例包装成函数并从中创建子图更短的方法。如果某个库或 matplotlib 中已经存在 subplot_hist 函数,就像 matlab 中存在的那样。
  • Seaborn 有一个 jointplot 函数,但它明确不允许在子图中使用。但我没有看到在示例代码前面放置def function 的问题。
  • 您还可以查看来自我尚未发布的文档更新的these alternatives。它们简化了创建单个这样的散点直方图;但不太适合创建子图。也就是说,您已经使用axes_grid1 方法在文档中找到了最佳选择。

标签: python matplotlib histogram scatter-plot scatter


【解决方案1】:

使用链接的示例,您需要做的就是增加subplots 的数量。

然后对于每个子图,您通过示例代码使每个子图成为散点直方图。

我在下面粘贴了一个玩具示例:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, axes = plt.subplots(figsize=(10,10),nrows=2, ncols=2)
print(axes)
colors = ['r','b','g','m']

for row in axes:
    for axScatter in row:
        print()
        x = np.random.randn(1000)
        y = np.random.randn(1000)
        # the scatter plot:
        # gets color from the end ('m' will be first)
        color = colors.pop()
        axScatter.scatter(x, y,color = color)
        axScatter.set_aspect(1.)

        # create new axes on the right and on the top of the current axes
        # The first argument of the new_vertical(new_horizontal) method is
        # the height (width) of the axes to be created in inches.
        divider = make_axes_locatable(axScatter)
        axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=axScatter)
        axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)

        # make some labels invisible
        axHistx.xaxis.set_tick_params(labelbottom=False)
        axHisty.yaxis.set_tick_params(labelleft=False)

        # now determine nice limits by hand:
        binwidth = 0.25
        xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
        lim = (int(xymax/binwidth) + 1)*binwidth

        bins = np.arange(-lim, lim + binwidth, binwidth)
        axHistx.hist(x, bins=bins,color=color)
        axHisty.hist(y, bins=bins, orientation='horizontal',color=color)

        # the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
        # thus there is no need to manually adjust the xlim and ylim of these
        # axis.

        axHistx.set_yticks([0, 50, 100])

        axHisty.set_xticks([0, 50, 100])

plt.show()

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 2015-08-27
    • 2020-12-10
    • 2017-02-05
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多