Matplotlib:在同一轴位置显示次要刻度和主要刻度 [英] Matplotlib: Display Minor Ticks and Major Ticks at the Same Axis Location

查看:76
本文介绍了Matplotlib:在同一轴位置显示次要刻度和主要刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含主要和次要蜱的情节.这是一个分组的条形图,我不希望使用图例来描述每个类别,但是希望每个类别都显示在较小的刻度中.然后我希望每个组在主要刻度中都有名称.

I have a plot with both Major and Minor Ticks. It is a grouped bar chart and I don't want the legend describing each category, but want each category shown in the minor ticks. Then I want each group to have the name in the major ticks.

我可以在一定程度上做到这一点,但主要刻度似乎覆盖了同一位置的次要刻度.如何关闭此功能?

I can do this to some extent, but the major tick seems to override the minor tick at the same location. How can I turn this off?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        0: [84, 41],
        1: [0, 0],
        2: [18.5, 3.5],
        3: [65.5, 124],
        4: [0.5, 0]
    },
    index = ['A', 'B']
)

ax = df.plot.bar(
    rot=0,
    legend=False,
    color=['gray', 'red', 'green', 'lightblue', 'darkblue',],
)

labels = df.unstack().index
label_x, label_mode = [], []

for rect, idx in zip(ax.patches, labels):
    print(rect, idx)
    label_mode.append(idx[0])
    label_x.append(rect.xy[0] + (rect.get_width() * 0.5))

ax.set_xticklabels(['A', 'B'])
ax.set_xticks(label_x, minor=True)
ax.set_xticklabels(label_mode, minor=True)
ax.tick_params(axis='x', which='minor', length=0)

ax.tick_params(axis='x', which='major', length=10, width=0)

推荐答案

这实际上非常简单.它是传递给 xaxis 对象的单个参数 remove_overlapping_locs.

This was actually very simple. It is a single parameter remove_overlapping_locs passed to xaxis object.

ax.xaxis.remove_overlapping_locs = False

请参阅matplotlib API更改 3.1.0 了解更多详情.

See matplotlib API changes 3.1.0 for more details.

这篇关于Matplotlib:在同一轴位置显示次要刻度和主要刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆