【问题标题】:How to add the second line of labels for axes如何为轴添加第二行标签
【发布时间】:2017-08-03 09:38:06
【问题描述】:

我正在尝试绘制一组不同类别的调查问题。

如图所示,Xlabel 是每个问题的名称。但我想在下面添加另一个带有类别名称的标签:[一般信息、技术、心理]。无论如何这样做,而不是使用 plt.text() 手动将其放入。我可以做的另一种方法是为条形的基于类别的颜色编码添加一个图例。但我认为放置第二个 xlabel 会更容易阅读。

【问题讨论】:

  • 你能提供你目前写的情节的代码吗?
  • 我担心最好的选择仍然是使用ax.text()。然后,您可以使用条形图的位置来很好地对齐文本。

标签: python matplotlib seaborn


【解决方案1】:

使用 '\n' 分隔刻度标签的级别,如下例所示:

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

【讨论】:

  • 从代码中我看不出为什么 A1A2 倾斜但 B C 没有。我更喜欢让它们倾斜。
  • 看看'label.set_rotation(45)'方法。
猜你喜欢
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多