我在matplotlib分的条形图中有两组,测量结果不同.我希望右边的那个有一个单独的y轴,以免相对于左边的那个看起来收缩.这就是我到目前为止try 过的:

代码 :

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

当前输出:

enter image description here

我怎样才能让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)

Output: enter image description here

Python相关问答推荐

单击Cookie横幅错误并在Selenium中启用搜索栏

X射线扫描显示Docker中的pip漏洞,尽管图像中未安装pip

Python中的锁定类和线程以实现dict移动

如何销毁框架并使其在tkinter中看起来像以前的样子?

Python中是否有方法从公共域检索搜索结果

如何处理嵌套的SON?

如何在Python中使用io.BytesIO写入现有缓冲区?

如何根据日期和时间将状态更新为已过期或活动?

返回nxon矩阵的diag元素,而不使用for循环

追溯(最近最后一次调用):文件C:\Users\Diplom/PycharmProject\Yolo01\Roboflow-4.py,第4行,在模块导入roboflow中

将输入管道传输到正在运行的Python脚本中

如果值不存在,列表理解返回列表

如何让程序打印新段落上的每一行?

加速Python循环

Telethon加入私有频道

如何使用pytest来查看Python中是否存在class attribution属性?

在Python中动态计算范围

ThreadPoolExecutor和单个线程的超时

什么是最好的方法来切割一个相框到一个面具的第一个实例?

如何排除prefecture_related中查询集为空的实例?