簡體   English   中英

Matplotlib 帶斷軸包第二個 Y 軸

[英]Matplotlib with brokenaxes package second Y-Axis

我使用brokenaxes包( https://github.com/bendichter/brokenaxes )來打破y 軸(//)。 現在我想要第二個 Y 軸,它也應該像第一個一樣斷開 (//)。

在下面的例子中我如何做到這一點?

import numpy as np
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
fig, ax = plt.subplots()
plt.gca().axes.get_yaxis().set_visible(False)

bax = brokenaxes(ylims=((0, 1.1), (60, 80)), hspace=.05)
x = np.linspace(0, 1, 100)
bax.plot(x, 5 * np.sin(10 * x) + 70)
bax.plot(x, 0.25* np.cos(40 * x) + 0.5, color="black")

ax2 = ax.twinx()
ax2.plot(x, 20 * np.sin(10 * x) + 50, color="green")

plt.show()

在此處輸入圖片說明

(在這個例子中,我使用了 ax.twinx,因為我無法讓它與brokenaxes包一起工作。此外,正弦和余弦曲線只是示例性的,在實際圖中,它們是交換的。)。

不確定,但我認為最好的解決方案是使用帶有一些調整的原subplots 這是一個基於Broken Axis的示例。 以下示例假設 y 軸具有不同的中斷區域:

# Based on https://matplotlib.org/gallery/subplots_axes_and_figures/broken_axis.html

import numpy as np
import matplotlib.pyplot as plt


# generate data
x = np.linspace(0, 1, 100)
yleft1 = 5 * np.sin(10 * x) + 70
yleft2 = 0.25 * np.cos(40 * x) + 0.5
yright = 20 * np.sin(10 * x) + 50

# Start with subplots
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(7, 7))
fig.subplots_adjust(hspace=0.05)

# ax1 - is the top subplot
# ax2 - is the bottom subplot

# prepare twinned axes
ax3 = ax1.twinx()
ax4 = ax2.twinx()

# set limits for left y-axis
ax1.set_ylim(58, 80)
ax2.set_ylim(0, 1.1)

# set limits for right y-axis (twinned)
ax3.set_ylim(58, 80)
ax4.set_ylim(0, 34)

# turn off spines
ax1.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax4.spines['top'].set_visible(False)

# setup ticks
ax1.tick_params(bottom=False)
ax2.tick_params(bottom=True)

# plotting break diagonals
d = 0.025  # line length 
ax1.plot((-d, +d), (-d, +d), c='k', clip_on=False, transform=ax1.transAxes)
ax1.plot((1 - d, 1 + d), (-d, +d), c='k', clip_on=False, transform=ax1.transAxes)
ax2.plot((-d, +d), (1 - d, (1 + d)), c='k', clip_on=False, transform=ax2.transAxes)
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), c='k', clip_on=False, transform=ax2.transAxes)


ax1.plot(x, yleft1, c='b', label='scale1')
ax2.plot(x, yleft1, c='b', label='scale1')

ax1.plot(x, yleft2, c='k', label='scale1')
ax2.plot(x, yleft2, c='k', label='scale1')

ax3.plot(x, yright, c='g', label='scale2')
ax4.plot(x, yright, c='g', label='scale2')

ax1.legend(loc=2)
ax3.legend(loc=1)

plt.show()

在此處輸入圖片說明

暫無
暫無

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

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