简体   繁体   中英

Arrows between matplotlib subplots

I decided to play around with this example code a bit. I was able to figure out how to draw a straight line between the two subplots, even when the line is outside the bounds of one of the subplots.

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

fig = plt.figure(figsize=(10, 5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
axs = [ax1, ax2]

# Fixing random state for reproducibility
np.random.seed(19680801)

# generate some random test data
all_data = [np.random.normal(0, std, 100) for std in range(6, 10)]

# plot violin plot
axs[0].violinplot(all_data,
                  showmeans=False,
                  showmedians=True)
axs[0].set_title('Violin plot')

# plot box plot
axs[1].boxplot(all_data)
axs[1].set_title('Box plot')

# adding horizontal grid lines
for ax in axs:
    ax.yaxis.grid(True)
    ax.set_xticks([y + 1 for y in range(len(all_data))])
    ax.set_xlabel('Four separate samples')
    ax.set_ylabel('Observed values')

for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(20)
plt.setp(axs[0], xticklabels=['x1', 'x2', 'x3', 'x4'])

transFigure = fig.transFigure.inverted()
coord1 = transFigure.transform(ax1.transData.transform([5,10]))
coord2 = transFigure.transform(ax2.transData.transform([2,-10]))
line = mpl.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                        c='k', lw=5, transform=fig.transFigure)
fig.lines.append(line)

Yes that added line is ugly but I just wanted to get it functional.

However, what I'd really like to do is make an arrow between the subplots, and I can't figure out how without jury-rigging my own arrow tails. Is there a way to do this that uses the matplotlib.pyplot.arrow class?

I also wanted to draw an arrow between two subplots but I didn't even know where to start! However, the line between subplots example in the original question gave me enough of a clue to get started...

First, I reduced the code in the original question to a minimal working example:

from matplotlib import lines, pyplot as plt

fig = plt.figure()

# First subplot
ax1 = fig.add_subplot(121)
plt.plot([0, 1], [0, 1])

# Second subplot
ax2 = fig.add_subplot(122)
plt.plot([0, 1], [0, 1])

# Add line from one subplot to the other
xyA = [0.5, 1.0]
ax1.plot(*xyA, "o")
xyB = [0.75, 0.25]
ax2.plot(*xyB, "o")
transFigure = fig.transFigure.inverted()
coord1 = transFigure.transform(ax1.transData.transform(xyA))
coord2 = transFigure.transform(ax2.transData.transform(xyB))
line = lines.Line2D(
    (coord1[0], coord2[0]),  # xdata
    (coord1[1], coord2[1]),  # ydata
    transform=fig.transFigure,
    color="black",
)
fig.lines.append(line)

# Show figure
plt.show()

This produces the following output:

子图之间的线

Then, using this blog post , I thought the answer was to create a matplotlib.patches.FancyArrowPatch and append it to fig.patches (instead of creating a matplotlib.lines.Line2D and appending it to fig.lines ). After consulting the matplotlib.patches.FancyArrowPatch documentation , plus some trial and error, I came up with something that works in matplotlib 3.1.2 :

from matplotlib import patches, pyplot as plt

fig = plt.figure()

# First subplot
ax1 = fig.add_subplot(121)
plt.plot([0, 1], [0, 1])

# Second subplot
ax2 = fig.add_subplot(122)
plt.plot([0, 1], [0, 1])

# Add line from one subplot to the other
xyA = [0.5, 1.0]
ax1.plot(*xyA, "o")
xyB = [0.75, 0.25]
ax2.plot(*xyB, "o")
transFigure = fig.transFigure.inverted()
coord1 = transFigure.transform(ax1.transData.transform(xyA))
coord2 = transFigure.transform(ax2.transData.transform(xyB))
arrow = patches.FancyArrowPatch(
    coord1,  # posA
    coord2,  # posB
    shrinkA=0,  # so tail is exactly on posA (default shrink is 2)
    shrinkB=0,  # so head is exactly on posB (default shrink is 2)
    transform=fig.transFigure,
    color="black",
    arrowstyle="-|>",  # "normal" arrow
    mutation_scale=30,  # controls arrow head size
    linewidth=3,
)
fig.patches.append(arrow)

# Show figure
plt.show()

However, as per the comments below, this does not work in matplotlib 3.4.2 , where you get this:

子图之间的箭头 - 不正确

Notice that the ends of the arrow do not line up with the target points (orange circles), which they should do.

This matplotlib version change also causes the original line example to fail in the same way.

However, there is a better patch! Use ConnectionPatch ( docs ), which is a subclass of FancyArrowPatch , instead of using FancyArrowPatch directly as the ConnectionPatch is designed specifically for this use case and deals with the transform more correctly, as shown in this matplotlib documentation example :

fig = plt.figure()

# First subplot
ax1 = fig.add_subplot(121)
plt.plot([0, 1], [0, 1]) 

# Second subplot
ax2 = fig.add_subplot(122)
plt.plot([0, 1], [0, 1]) 

# Add line from one subplot to the other
xyA = [0.5, 1.0]
ax1.plot(*xyA, "o")
xyB = [0.75, 0.25]
ax2.plot(*xyB, "o")
# ConnectionPatch handles the transform internally so no need to get fig.transFigure
arrow = patches.ConnectionPatch(
    xyA,
    xyB,
    coordsA=ax1.transData,
    coordsB=ax2.transData,
    # Default shrink parameter is 0 so can be omitted
    color="black",
    arrowstyle="-|>",  # "normal" arrow
    mutation_scale=30,  # controls arrow head size
    linewidth=3,
)
fig.patches.append(arrow)

# Show figure
plt.show()

This produces the correct output in both matplotlib 3.1.2 and matplotlib 3.4.2 , which looks like this:

在此处输入图片说明

To draw a correctly positioned line connecting across two subplots in matplotlib 3.4.2 , use a ConnectionPatch as above but with arrowstyle="-" (ie no arrow heads, so just a line).

NB: You cannot use:

  • plt.arrow as it is automatically added to the current axes so only appears in one subplot

  • matplotlib.patches.Arrow as the axes-figure transform skews the arrow-head

  • matplotlib.patches.FancyArrow as this also results in a skewed arrow-head

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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