簡體   English   中英

如何將軸添加到 Matplotlib 圖?

[英]How to add axes to the Matplotlib plot?

如何在此處給出的代碼中將另一個斧頭添加到右上角的繪圖中原圖

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

# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, axScatter = plt.subplots(figsize=(5.5, 5.5))

# the scatter plot:
axScatter.scatter(x, y)
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)
axHisty.hist(y, bins=bins, orientation='horizontal')

# 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.draw()
plt.show()

所以生成的圖像是這樣的Desired_Image

我嘗試使用:: ax_cnr = divider.append_axes("right", 1.2, pad=0.1)添加另一個軸,但它沒有提供所需的輸出! 請幫忙!

上面使用plt.subplots_mosaic的答案是一個很好的答案,但我相信 suplots_mosaic 目前是一個實驗性/臨時 API,所以我想提供一個使用plt.subplots()並使用gridspec_kw操作軸的解決方案:

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)

# Start figure
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(5.5, 5.5), sharex='col', sharey='row', gridspec_kw={'height_ratios': [1, 3], 'width_ratios': [3, 1], 'hspace': 0.05, 'wspace': 0.05})

# Define/name each axes
axScatter = axs[1, 0]  # bottom left
axHistx = axs[0, 0]  # top left
axHisty = axs[1, 1]  # bottom right
new_axis = axs[0, 1]  # new axis - top right

# the scatter plot:
axScatter.scatter(x, y)
axScatter.set_aspect(1.)

# 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)
axHisty.hist(y, bins=bins, orientation='horizontal')

# Hist axes
axHistx.set_yticks([0, 50, 100])
axHisty.set_xticks([0, 50, 100])

plt.draw()
plt.show()

結果如下: Figure with new axes

您可以在 Matplotlib 的軸教程 ( https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html ) 中找到有關操作軸的更多信息。

我不直接了解make_axes_locatable代碼,但是可以使用這樣的mosaic來解決這個問題:

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)

fig, axs = plt.subplot_mosaic([['a)', 'a)', 'd)'],
                               ['b)', 'b)', 'c)'],
                               ['b)', 'b)', 'c)']],
                              constrained_layout=True)

axs['b)'].scatter(x, y)

# make some labels invisible
axs['a)'].xaxis.set_tick_params(labelbottom=False)
axs['c)'].yaxis.set_tick_params(labelleft=False)
axs['d)'].xaxis.set_tick_params(labelbottom=False)
axs['d)'].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)
axs['a)'].hist(x, bins=bins)
axs['c)'].hist(y, bins=bins, orientation='horizontal')

axs['a)'].set_yticks([0, 50, 100])
axs['c)'].set_xticks([0, 50, 100])

axs['b)'].set_xticks([-4, -2, 0, 2, 4])
axs['b)'].set_yticks([-4, -2, 0, 2, 4])

這顯示了與原始內容類似的內容:

w/適當的軸

'd)'軸可以通過axs['d)'].<do stuff here>()

抱歉命名晦澀,我從這里復制粘貼了一個馬賽克示例,並以此為基礎工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM