【问题标题】:Add either a density or box plot to the margins of a plot in Matplotlib在 Matplotlib 中的绘图边缘添加密度图或箱线图
【发布时间】:2015-11-25 22:33:13
【问题描述】:

我有一个线性比例的散点图。我想从Marginal Histograms and Box Charts 向我的散点图like this figure 的边距(左侧和底部)添加一个箱线图?

更新 这是我目前的工作解决方案,请分享您的想法或提出更好的建议。

ax.plot(df['vcnt'],  df['ecnt'], 'ko', alpha=0.5)
# Save the default tick positions, so we can reset them..

tcksx = ax.get_xticks()
tcksy = ax.get_yticks()

ax.boxplot(df['ecnt'], positions=[min(tcksx)], notch=True, widths=1.)
ax.boxplot(df['vcnt'], positions=[min(tcksy)], vert=False, notch=True, widths=1.)

ax.set_yticks(tcksy) # pos = tcksy
ax.set_xticks(tcksx) # pos = tcksx
ax.set_yticklabels([int(j) for j in tcksy])
ax.set_xticklabels([int(j) for j in tcksx])
ax.set_ylim([min(tcksy-1),max(tcksy)])
ax.set_xlim([min(tcksx-1),max(tcksx)])

【问题讨论】:

    标签: python matplotlib plot boxplot margins


    【解决方案1】:

    您可以通过为条形图创建额外的axes 来实现此目的。

    import pandas as pd
    from matplotlib import pyplot as plt
    import numpy as np
    
    x_data = np.random.randn(100)
    y_data = -x_data + np.random.randn(100)*0.5
    
    df = pd.DataFrame()
    df['vcnt'] = x_data
    df['ecnt'] = y_data
    
    
    left = 0.1
    bottom = 0.1
    top = 0.8
    right = 0.8
    main_ax = plt.axes([left,bottom,right-left,top-bottom])
    # create axes to the top and right of the main axes and hide them
    top_ax = plt.axes([left,top,right - left,1-top])
    plt.axis('off')
    right_ax = plt.axes([right,bottom,1-right,top-bottom])
    plt.axis('off')
    main_ax.plot(df['vcnt'],  df['ecnt'], 'ko', alpha=0.5)
    # Save the default tick positions, so we can reset them..
    
    tcksx = main_ax.get_xticks()
    tcksy = main_ax.get_yticks()
    
    right_ax.boxplot(df['ecnt'], positions=[0], notch=True, widths=1.)
    top_ax.boxplot(df['vcnt'], positions=[0], vert=False, notch=True, widths=1.)
    
    main_ax.set_yticks(tcksy) # pos = tcksy
    main_ax.set_xticks(tcksx) # pos = tcksx
    main_ax.set_yticklabels([int(j) for j in tcksy])
    main_ax.set_xticklabels([int(j) for j in tcksx])
    main_ax.set_ylim([min(tcksy-1),max(tcksy)])
    main_ax.set_xlim([min(tcksx-1),max(tcksx)])
    
    # set the limits to the box axes
    top_ax.set_xlim(main_ax.get_xlim())
    top_ax.set_ylim(-1,1)
    right_ax.set_ylim(main_ax.get_ylim())
    right_ax.set_xlim(-1,1)
    
    
    
    plt.show()
    

    【讨论】:

    • 很好,正是我想要的。
    • 我通过仅将 matplotlib.axes 对象传递给函数来生成上面的图。现在我有一个figure,我有一个add_subplots,其中一个是我的ax 对象。所以我的ax 就等于你的main_ax,对吧?
    • 是的。所以现在你必须要么传递三个轴,要么在函数内生成其他轴。
    猜你喜欢
    • 2020-09-16
    • 2023-03-24
    • 1970-01-01
    • 2015-06-29
    • 2013-09-06
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多