从投影的 2d 直方图绘制对齐的 x,y 1d 直方图 [英] Plot aligned x,y 1d histograms from projected 2d histogram

查看:56
本文介绍了从投影的 2d 直方图绘制对齐的 x,y 1d 直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一张类似于

区别在于,我没有使用二维的分散点,而是使用numpy的histogram2d生成了二维直方图,并使用 imshow gridspec 进行了绘制:

如何将这个 2D 直方图投影到水平和垂直直方图(或曲线)中,使其看起来对齐,就像第一张图片一样?

<小时>

将 numpy 导入为 np导入matplotlib.pyplot作为plt导入 matplotlib.gridspec 作为 gridspec数据=#已上传到http://pastebin.com/tjLqM9gQ# 创建坐标 (0,1,...,N) 乘以 (0,1,...,N) 的网格y,x = np.mgrid [:len(data [0,:,0]),:len(data [0,0,:])]# 复制网格xcoord,ycoord = np.array([x] * len(data)),np.array([y] * len(data))# 计算坐标为 x,y 的直方图h,xe,ye = np.histogram2d(xcoord.ravel(),ycoord.ravel(),bins=[len(data[0, 0, :]), len(data[0, :, 0])],weights = stars.ravel())# 投影直方图 inx 和 yhx, hy = h.sum(axis=0), h.sum(axis=1)#定义图形的大小无花果= plt.figure(figsize =(20,15))gs = gridspec.GridSpec(10,12)#定义子图的位置.ax0 = plt.subplot(gs [6:10,5:9])axx = plt.subplot(gs[5:6, 5:9])axy = plt.subplot(gs [6:10,9:10])ax0.imshow(h, cmap=plt.cm.viridis, 插值='最近',原点='较低',vmin=0.)# 删除刻度标签nullfmt = NullFormatter()axx.xaxis.set_major_formatter(nullfmt)axx.yaxis.set_major_formatter(nullfmt)axy.xaxis.set_major_formatter(nullfmt)axy.yaxis.set_major_formatter(nullfmt)# 顶部图axx.plot(hx)axx.set_xlim(ax0.get_xlim())#右图axy.plot(hy,range(len(hy)))axy.set_ylim(ax0.get_ylim())fig.tight_layout()plt.savefig('del.png')

解决方案

如果您对边际分布都保持直立感到满意,则可以使用

I need to generate an image similar to the one shown in this example:

The difference is that, instead of having the scattered points in two dimensions, I have a two-dimensional histogram generated with numpy's histogram2d and plotted using with imshow and gridspec:

How can I project this 2D histogram into a horizontal and a vertical histogram (or curves) so that it looks aligned, like the first image?


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

data = # Uploaded to http://pastebin.com/tjLqM9gQ

# Create a meshgrid of coordinates (0,1,...,N) times (0,1,...,N)
y, x = np.mgrid[:len(data[0, :, 0]), :len(data[0, 0, :])]
# duplicating the grids
xcoord, ycoord = np.array([x] * len(data)), np.array([y] * len(data))
# compute histogram with coordinates as x,y
h, xe, ye = np.histogram2d(
    xcoord.ravel(), ycoord.ravel(),
    bins=[len(data[0, 0, :]), len(data[0, :, 0])],
    weights=stars.ravel())

# Projected histograms inx and y
hx, hy = h.sum(axis=0), h.sum(axis=1)

# Define size of figure
fig = plt.figure(figsize=(20, 15))
gs = gridspec.GridSpec(10, 12)

# Define the positions of the subplots.
ax0 = plt.subplot(gs[6:10, 5:9])
axx = plt.subplot(gs[5:6, 5:9])
axy = plt.subplot(gs[6:10, 9:10])

ax0.imshow(h, cmap=plt.cm.viridis, interpolation='nearest',
           origin='lower', vmin=0.)

# Remove tick labels
nullfmt = NullFormatter()
axx.xaxis.set_major_formatter(nullfmt)
axx.yaxis.set_major_formatter(nullfmt)
axy.xaxis.set_major_formatter(nullfmt)
axy.yaxis.set_major_formatter(nullfmt)

# Top plot
axx.plot(hx)
axx.set_xlim(ax0.get_xlim())
# Right plot
axy.plot(hy, range(len(hy)))
axy.set_ylim(ax0.get_ylim())

fig.tight_layout()
plt.savefig('del.png')

解决方案

If you are ok with the marginal distributions all being upright, you could use corner

E.g.:

import corner
import numpy as np
import pandas as pd

N = 1000

CORNER_KWARGS = dict(
    smooth=0.9,
    label_kwargs=dict(fontsize=30),
    title_kwargs=dict(fontsize=16),
    truth_color="tab:orange",
    quantiles=[0.16, 0.84],
    levels=(1 - np.exp(-0.5), 1 - np.exp(-2), 1 - np.exp(-9 / 2.0)),
    plot_density=False,
    plot_datapoints=False,
    fill_contours=True,
    max_n_ticks=3,
    verbose=False,
    use_math_text=True,
)


def generate_data():
    return pd.DataFrame(dict(
        x=np.random.normal(0, 1, N),
        y=np.random.normal(0, 1, N)
    ))


def main():
    data = generate_data()
    fig = corner.corner(data, **CORNER_KWARGS)
    fig.show()


if __name__ == "__main__":
    main()

这篇关于从投影的 2d 直方图绘制对齐的 x,y 1d 直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆