简体   繁体   English

如何将轴添加到 Matplotlib 图?

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

How to add another ax to a plot on the right corner in this code given here如何在此处给出的代码中将另一个斧头添加到右上角的绘图中原图

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()

So that the resulting image is something like this所以生成的图像是这样的Desired_Image

I tried to add another axis by using:: ax_cnr = divider.append_axes("right", 1.2, pad=0.1) But it is not giving the desired output!!我尝试使用:: ax_cnr = divider.append_axes("right", 1.2, pad=0.1)添加另一个轴,但它没有提供所需的输出! Kindly help!请帮忙!

The answer above using plt.subplots_mosaic is a good answer but I believe suplots_mosaic is currently an experimental/provisional API so I wanted to offer a solution using plt.subplots() and manipulating the axes using gridspec_kw :上面使用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()

Here is the result: Figure with new axes .结果如下: Figure with new axes

You can find more info about manipulating axes in Matplotlib's Axes Tutorial ( https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html ).您可以在 Matplotlib 的轴教程 ( https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html ) 中找到有关操作轴的更多信息。

I don't know about the make_axes_locatable code directly, but one could work around this with a mosaic like so:我不直接了解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])

which shows something similar to the original:这显示了与原始内容类似的内容:

w/适当的轴

the 'd)' axis is accessible with just axs['d)'].<do stuff here>() 'd)'轴可以通过axs['d)'].<do stuff here>()

Sorry about the obscure naming, I copypasted a mosaic example from here and worked from that.抱歉命名晦涩,我从这里复制粘贴了一个马赛克示例,并以此为基础工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM