python - 如何为轴添加第二行标签

标签 python matplotlib seaborn

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

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

enter image description here

最佳答案

如本例所示,使用“\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()

enter image description here

关于python - 如何为轴添加第二行标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42762486/

相关文章:

python - 如何在不使用 pyplot 的情况下在 matplotlib 中创建绘图

python - 在 `import` 语句之前更改模块对象?

python - seaborn 的 lmplot : KeyError [ . ..] 不在索引中; excel 和 csv 导入

python - Seaborn PairPlot 的正确对角线 Y 轴

python - 日期列中的 Pandas 多个日期范围

Python scikit 学习多类多标签性能指标?

python - 运行时错误 : Can not put single artist in more than one figure when using matplotlib 1. 5

python - 将 matplotlib 颜色图转换为 seaborn 调色板

python - 如何在 IntelliJ 中制作 pytest 案例 "runnable"

python - 比较两个恒星 x-y 坐标列表以查找匹配的物体