Skip to main content
 首页 » 编程设计

python之在matplotlib中自动缩写长度字符串

2025年05月04日28findumars

如果有与相邻文本冲突的情况,有没有一种方法可以自动减少matplotlib中字符串的长度,例如:


我要寻找的是如果matplotlib检测到与另一文本的冲突,它将自动减少这些文本,以使所有文本都可读。

请注意,当然可以使用rotate the labels或make the fontsize smaller来防止重叠。但是在这里,我想问如何在重叠的情况下剪切文本。

请您参考如下方法:

您可以旋转刻度标签。

%matplotlib inline  
import matplotlib.pyplot as plt 
 
countries = ["United Arab Emirates", "Central African Republic", "Bosnia and Herzegovina"] 
population = [9770529, 4745185, 3301000] 
 
 
x = plt.bar(range(len(countries)), population) 
 
plt.title("Countries in the world by population (2019)")      
plt.ylabel("population")    
 
plt.xticks(range(len(countries)), countries, rotation='40') 
plt.yscale('log') 
 
plt.show()