如何获得具有交替距离的xticks? [英] How to obtain xticks with alternating distances?

查看:79
本文介绍了如何获得具有交替距离的xticks?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个条形图,其中 x 轴具有国家/地区的 2 个字母标签.我必须选择一个非常小的字体,所以 x-ticks 不会相互重叠.有什么方法可以指定 x-ticks 和 x 轴之间的距离,以便我可以选择更大的字体而不会重叠标签?

I have a bar plot where the x-axis has the 2-letter labels of countries. I have to choose a very small font, so the x-ticks do not overlap with each other. Is there any way to assign a distance between x-ticks and the x-axis, so I can choose a larger font without labels being overlapped?

目前:

所需示例:

axis:  ----------------------
ticks: c1  c3  ...
         c2  c4   ...

推荐答案

一种方法是在交替位置创建较小的刻度并赋予它们更大的刻度长度.主要刻度的 MultipleLocator 为 2 将它们每 2 放置一次.为次刻度添加 1 的 MultipleLocator 填补了空白,因为主要刻度会自动抑制重叠的次要刻度职位.可以使勾号的颜色变浅,以获得更大的勾号和标签之间的对比度.

An approach is to create minor ticks at the alternating positions and give them a larger tick length. A MultipleLocator of 2 for the major ticks puts them every 2. Adding a MultipleLocator of 1 for the minor ticks fills in the gaps, as major ticks automatically suppress minor ticks in overlapping positions. The color of the ticks can be made lighter to obtain more contrast between the ticks and the labels.

当通过 seaborn 或 pandas 生成绘图时,只要可以提供明确的标签列表,相同的方法就可以工作.

The same approach would work when the plot would be generated via seaborn or pandas, as long as an explicit list of labels can be provided.

from matplotlib import pyplot as plt
from matplotlib import ticker
import numpy as np

letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
N = 80
names = [letters[i // 26] + letters[i % 26] for i in range(N)]
values = np.random.binomial(100, 0.1, N)

cmap = plt.cm.get_cmap('rainbow')
colors = [cmap(i / N) for i in range(N)]
plt.bar(names, values, color=colors)
ax = plt.gca()
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
ax.xaxis.set_minor_formatter(ticker.IndexFormatter(names))
ax.tick_params(axis='x', which='minor', length=15)
ax.tick_params(axis='x', which='both', color='lightgrey')
ax.autoscale(enable=True, axis='x', tight=True)

plt.show()

PS:@MadPhysicist 从评论中添加换行符的想法更简单.看起来有点不同:

PS: @MadPhysicist's idea from the comments to add newlines is even simpler. It looks a bit different:

from matplotlib import pyplot as plt
import numpy as np

letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
N = 80
names = [('\n' if i % 2 == 1 else '') + letters[i // 26] + letters[i % 26] for i in range(N)]
values = np.random.binomial(100, 0.1, N)

cmap = plt.cm.get_cmap('rainbow')
colors = [cmap(i / N) for i in range(N)]
plt.bar(names, values, color=colors)
plt.gca().autoscale(enable=True, axis='x', tight=True)
plt.show()

这篇关于如何获得具有交替距离的xticks?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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