如何为轴添加第二行标签 [英] How to add the second line of labels for axes
问题描述
我正在尝试绘制一组不同类别的调查问题.
I am trying to plot a set of survey question in different categories.
如图所示,Xlabel是每个问题的名称.但我想在类别名称下方添加另一个标签:[一般信息、技术、心理].无论如何,而不是使用plt.text()手动将其放入.我可以做的另一种方法是为栏的基于类别的颜色编码添加图例.但我认为放置第二个 xlabel 使其更易于阅读.
As shown in the picture, the Xlabel is the name of each question. But I want to add another label underneath with the name of the category: [general info, technical, psychological]. Anyway of doing that instead of manually putting it in using the plt.text(). Another way I can do is to put a legend in for the category based color coding of the bar. But I think putting a second xlabel makes it easier to read.
推荐答案
使用 '\n' 来分隔刻度标签的级别,如下例所示:
Use the '\n' to separate tick labels' levels like in this example:
import numpy as np
import matplotlib.pyplot as plt
ind = np.arange(3)
width = .2
x = list()
# x labels position: i = 1st bar, i+w/2 = category, i+w = 2nd bar
for i in ind:
x.extend([i, i+width/2., i+width])
# plot bars
fig = plt.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, [1, 3, 5], width, color='r', align = 'center')
rects2 = ax.bar(ind+width, [2, 4, 6], width, color='g', align = 'center')
# set ticks and labels
plt.xticks(x)
ax.set_xticklabels(('A1','\n\nGeneral Info', 'A2', 'B1','\n\nTechnical', 'B2', 'C1','\n\nPsycological', 'C2'),ha='center')
# hide tick lines for x axis
ax.tick_params(axis='x', which='both',length=0)
# rotate labels with A
for label in ax.get_xmajorticklabels():
if 'A' in label.get_text(): label.set_rotation(45)
plt.show()
这篇关于如何为轴添加第二行标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!