Skip to main content
 首页 » 编程设计

python之matplotlib barplot 不适用于对数刻度

2024年12月31日12exmyth

我正在尝试在 Matplotlib 中以对数刻度绘制条形图。如果我手动执行此操作(下图 3),我会得到正确的答案,但如果我使用 matplotlib 的 set_yscale('log') 或使用条形图的 log 属性,我会得到错误的图。因此,正如您在图 1 和图 2 中看到的那样,绘图是错误的,因为 log10(y2) = ([ 5.7363965 , 5.77815125])

下面是一个MWE:

from __future__ import division 
import numpy as np 
from matplotlib import pyplot as plt 
 
ind = np.array(['US', 'EU']) 
y2 = [545000, 600000] 
 
fig = plt.figure(1) 
ax = fig.add_subplot(1, 1, 1) 
plt.bar(ind, y2) 
ax.set_yscale('log') 
plt.title('example 1') 
#plt.savefig('../../Desktop/ex1.jpg') 
 
fig = plt.figure(2) 
ax2 = fig.add_subplot(1, 1, 1) 
plt.bar(ind, y2, log=True) 
plt.title('example2') 
#plt.savefig('../../Desktop/ex2.jpg') 
 
 
fig2 = plt.figure(3) 
ax1 = fig2.add_subplot(1, 1, 1) 
plt.bar(ind, np.log10(y2)) 
plt.title('example 3') 
#plt.savefig('../../Desktop/ex3.jpg') 
plt.show() 

下面是数字:

请您参考如下方法:

如果您使用 print(plt.gca().get_ylim()) 查看第一个图中的 y 轴限制,我得到:

(542386.3669524404, 602891.2596703834) 

因此,在问题的图 1 和图 2 中,对数刻度中只能看到 1 个主要刻度。要获得与第 3 个类似的图表,您需要设置 y 轴的限制:

ind = np.array(['US', 'EU']) 
y2 = [545000, 600000] 
 
fig = plt.figure(1) 
ax = fig.add_subplot(1, 1, 1) 
plt.bar(ind, y2) 
plt.ylim(1,1000000)  # set y axis limits 
ax.set_yscale('log') 
plt.title('example 1') 
 
plt.show()