将长xtick分为两行matplotlib

2024-10-01 13:31:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下matplotlib

我想把x记号分成2行而不是1行,因为有时它们很长,所以它们会碰到另一行,然后就不可能读取x记号了。在

请记住,X记号不是硬编码的,它们正在变化。所以不总是相同的x记号。

因此,对于下面的示例,如果我有而不是to Schleswig-Holstein我可以有:

to Schleswig-
  Holstein

我如何将-后面的字符串放入换行符的换行符中?或者简单地说10个字母之后,我想换一行

顺便说一句,如果我能像上面的例子一样将所有文本居中也会很好

所以下面的也可以,但不是最好的。在

^{pr2}$

plot

PS:我使用的代码如下:

# create figure
fig = plt.figure()

# x-Axis (sites)
i = np.array(i)
i_pos = np.arange(len(i))

# y-Axis (values)
u = urbs_values
o = oemof_values

plt.bar(i_pos-0.15, list(u.values()), label='urbs', align='center', alpha=0.75, width=0.2)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
plt.bar(i_pos+0.15, list(o.values()), label='oemof', align='center', alpha=0.75, width=0.2)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))

# tick names
plt.xticks(i_pos, list(map((' to ').__add__, list(u.keys()))))

# plot specs
plt.xlabel('Lines')
plt.ylabel('Capacity [MW]')
plt.title(site+' '+name)
plt.grid(True)
plt.legend()
plt.ticklabel_format(style='sci', axis='y')
# plt.show()

# save plot
fig.savefig(os.path.join(result_dir, 'comp_'+name+'_'+site+'.png'), dpi=300)
plt.close(fig)

Tags: toposformatstylefigpltlistfigure
1条回答
网友
1楼 · 发布于 2024-10-01 13:31:52

您可以按照this应答中的建议使用re,并在每10个字符后添加一个新行字符来创建一个新标签列表。在

import re
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

xlabels = ["to Schleswig-Holstein", "to Mecklenburg-Vorpommern", r"to Lower Saxony"]

xlabels_new = [re.sub("(.{10})", "\\1\n", label, 0, re.DOTALL) for label in xlabels]

plt.plot(range(3))
plt.xticks(range(3), xlabels_new)
plt.show()

enter image description here

备选方案

^{pr2}$

enter image description here

相关问题 更多 >