简体   繁体   English

如何使用 matplotlib 在一个图中截断子图 y 轴上非常长的刻度标签并整齐地适合 plot 和标签?

[英]How to truncate very long tick labels on y-axis of subplots and fit plot and labels neatly in one fig using matplotlib?

Below is my code.下面是我的代码。 I would like to truncate the y-axis tick labels.我想截断 y 轴刻度标签。 I can't truncate the field that is being used for the labels because then the data will aggregate improperly.我无法截断用于标签的字段,因为这样数据将不正确地聚合。 I need to truncate the strings being used for the label.我需要截断用于 label 的字符串。 Let's say the first 100 characters per string.假设每个字符串的前 100 个字符。 How would I truncate for each subplot in this manner to be able to neatly show all the labels and subplots in one figure?我将如何以这种方式截断每个子图,以便能够在一个图中整齐地显示所有标签和子图?

fig, ax = plt.subplots(2,2, sharex = True, figsize=(15,10))

a = q3[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,  ax = ax[0,0])
b = q1[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[0,1])
c = q4[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[1,0])
d = q2[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[1,1])


plt.show()

在此处输入图像描述

I can't truncate the field that is being used for the labels because then the data will aggregate improperly.我无法截断用于标签的字段,因为这样数据将不正确地聚合。

By default, pandas uses the index to set the tick labels.默认情况下,pandas 使用索引来设置刻度标签。 However, you can create another column of truncated labels and then tell pandas to use that for setting the y-tick labels.但是,您可以创建另一列截断标签,然后告诉 pandas 使用它来设置 y 刻度标签。

q3.plot(kind='barh', ..., yticks=q3['my_column_with_truncated_strings'])

Alternatively, you can use matplotlib directly:或者,您可以直接使用 matplotlib:

axes[0,0].set_yticklabels(q3['my_column_with_truncated_strings'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM