gpt4 book ai didi

python - 将长 xticks 分成 2 行 matplotlib

转载 作者:行者123 更新时间:2023-12-02 03:18:59 26 4
gpt4 key购买 nike

我有以下 matplotlib

我想将 x-ticks 分成 2 行而不是 1 行,因为有时它们太长了,这就是为什么它们会越过另一行,然后就不可能读取 x-ticks。

牢记 X-ticks 不是硬编码的,它们在变化。所以并不总是相同的 x-ticks。

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

to Schleswig-
Holstein

我如何将 - 之后的字符串放入换行符的 x 刻度?或者只是在说 10 个字母后我想换行

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

所以跟随也可以,但不是最好的。

to Schleswig-
Holstein

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)

最佳答案

您可以按照 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

备选

xlabels_new = [label.replace('-', '-\n') for label in xlabels]

enter image description here

关于python - 将长 xticks 分成 2 行 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55375156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com