我在
matplotlib
的条形图中有两组,具有不同尺度的测量值。我希望右侧的轴有一个单独的 y 轴,以免相对左侧的轴显得收缩。这是我到目前为止所尝试过的:
代码:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 300
plt.rcParams['font.size'] = 14
# set width of bars
barWidth = 0.15
bars1 = [10, 0.5]
bars2 = [11, 0.8]
bars3 = [20, 1.0]
bars4 = [30, 1.5]
bars5 = [40, 1.8]
# Set position of bar on X axis
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
r5 = [x + barWidth for x in r4]
# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white')
ax.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white')
ax.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r4, bars4, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r5, bars5, color='#2d7f5e', width=barWidth, edgecolor='white')
# Create secondary y-axis for the right group
ax2 = ax.twinx()
ax2.set_ylabel('scale2', fontweight='bold', labelpad=10)
group_labels = ['group1', 'group2']
ax.set_xlabel('Datasets', fontweight='bold', labelpad=10)
ax.set_ylabel('scale1', fontweight='bold', labelpad=10,)
ax.set_xticks([r + 2 * barWidth for r in range(len(bars1))])
ax.set_xticklabels(group_labels)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
电流输出:
怎样才能让
group2
只受scale2
影响?
您需要为 group2 的元素调用
ax2.bar
,如下所示:
# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax2 = ax.twinx()
for r, bar, color in zip([r1, r2, r3, r4, r5],
[bars1, bars2, bars3, bars4, bars5],
['#7f6d5f', '#557f2d'] + ['#2d7f5e'] * 3):
kwargs = {'color': color,
'width': barWidth,
'edgecolor': 'white'}
ax.bar(r[0], bar[0], **kwargs)
ax2.bar(r[1], bar[1], **kwargs)