matplotlib中的条形图在x坐标上具有较大范围时显示较少的条形图 [英] Bar chart in matplotlib shows less bars when having big range on x coordinates
问题描述
我在这里用python和matplotlib中的条形图做错了什么?第一个图是好的,第二个图在x轴上的范围更大,最大到1500.请注意,在第二个图中,低比例尺上的大多数条消失了,但未显示1500的条.
What am I doing wrong here with a bar chart in python and matplotlib? The first plot is good, the second has a much wider range on the x-axis up to 1500. Notice in the second plot that most of the bars on the low scale disappear, but also the bar at 1500 is not shown.
我尝试在bar()方法中设置width = 0.8,但这无济于事.
I tried setting the width=0.8 in the bar() method, but that does not help.
使用对数x轴(使用plt.xscale('log'))似乎可以正常工作
With a logarithmic x-axis (using plt.xscale('log') ) it seems to work fine
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(12, 6))
plt.bar(np.array([1,2,3,4,11,12]), np.array([10,2,1,1,3,10]))
plt.show()
#Then I close the figure and run this:
plt.bar(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]))
plt.show()
推荐答案
条默认情况下为1个数据单元宽.轴宽约600像素,但约有1500个单位.因此,您看到任何单个柱的机会为600/1500*1 = 40%
.从这种意义上来说,很不幸,您没有看到x = 1500处的柱线.其他条形图之间的距离非常近,您看不到实际上显示了其中一个.
Bars are by default 1 data units wide. The axes is ~600 pixels wide, but has ~1500 units. The chances you will see any single bar is hence 600/1500*1 = 40%
. In that sense it's bad luck that you don't see the bar at x=1500. The other bars are so close together that you don't see which one of them is actually shown.
您宁愿使条形图足够宽以便可以安全地看到它,而不是依赖于看到条形图的机会.例如.使用5的宽度
Instead of relying on the chances of seeing a bar, you would rather make the bar wide enough such that it can be seen safely. E.g. using a width of 5
plt.bar(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]), width=5)
或者,您还可以显示一个茎图,即用线代替条的图.
Alternatively you could also show a stem plot, i.e. a plot with lines instead of bars,
plt.stem(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]),markerfmt=" ", basefmt=" ")
plt.ylim(0,None)
这篇关于matplotlib中的条形图在x坐标上具有较大范围时显示较少的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!