我想要一個由散點圖和散點圖右側和下方的 2 個直方圖組成的表示。我有以下要求: 1.) 在散點圖中,縱橫比相等,因此圓看起來不像橢圓。2.) 在圖形中,子圖應與散點圖軸的寬度或高度完全相同。
這也在有限的范圍內起作用。但是,我不能使下直方圖與散點圖的 x 軸一樣寬。我怎么做?
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import random
#create some demo data
x = [random.uniform(-2.0, 2.0) for i in range(100)]
y = [random.uniform(-2.0, 2.0) for i in range(100)]
#create figure
fig = plt.figure()
gs = gridspec.GridSpec(2, 2, width_ratios = [3, 1], height_ratios = [3, 1])
ax = plt.subplot(gs[0])
# Axis labels
plt.xlabel('pos error X [mm]')
plt.ylabel('pos error Y [mm]')
ax.grid(True)
ax.axhline(color="#000000")
ax.axvline(color="#000000")
ax.set_aspect('equal')
radius = 1.0
xc = radius*np.cos(np.linspace(0,np.pi*2))
yc = radius*np.sin(np.linspace(0,np.pi*2))
plt.plot(xc, yc, "k")
ax.scatter(x,y)
hist_x = plt.subplot(gs[1],sharey=ax)
hist_y = plt.subplot(gs[2],sharex=ax)
plt.tight_layout() #needed. without no xlabel visible
plt.show()

我想要的是:

非常感謝您的幫助!
uj5u.com熱心網友回復:
最簡單(但不一定最優雅)的解決方案是在應用緊密布局后手動定位較低的直方圖:
ax_pos = ax.get_position()
hist_y_pos = hist_y.get_position()
hist_y.set_position((ax_pos.x0, hist_y_pos.y0, ax_pos.width, hist_y_pos.height))

此輸出由 matplotlib 3.4.3 版生成。對于您的示例輸出,您顯然使用了不同的版本,因為我得到的直方圖比您寬得多。
(我保留了您的示例中的直方圖名稱,盡管我猜較低的名稱應該是hist_x而不是hist_y)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350094.html
標籤:Python matplotlib
