我是matplotlib的新用户,我有图表barh的问题:重叠条。 绘制图形时,条形图重叠,我没有找到原因。在我看来,问题在于重新调整图表的大小。我重新调整它的大小,因为将来我会插入标题,图例和x,y描述。我尝试了一些解决方案,但我有一个解决方案! 这是我的代码:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from matplotlib.colors import LightSource
from matplotlib.artist import Artist
import numpy as np
from decimal import *
import datetime
#Size
width = 360
height = 240
dpi = 80.0
colors = ['#be1e2d',
'#666699',
'#92d5ea',
'#ee8310',
'#8d10ee',
'#5a3b16',
'#26a4ed',
'#f45a90',
'#e9e744']
#Data
columns = ['2005','2006']
data = [[2.6,3.5],[2, 1.5]]
linewidth = 1
N = len(columns)
ind = np.arange(N)
#Re-Size
rdata = len(data) if columns is None else len(columns)
heightColumn = height*1.0 / (rdata) / (len(columns))
heightColumn = heightColumn/dpi
fig = plt.figure(1, figsize=(width/dpi,height/dpi),facecolor='w')
ax = fig.add_axes([0.2, 0.3, 0.6, 0.5])
#Draw
tupleRects = ()
idxColor = 0
valPositionCol = ind
for dat in data:
rects = plt.barh(valPositionCol, dat, heightColumn, color=colors[idxColor], alpha=0.8,
linewidth=linewidth)
valPositionCol=valPositionCol+heightColumn
idxColor += 1
if idxColor==9:
idxColor = 0
tupleRects += (rects,)
plt.show()
感谢
代码相同,但我更改了数据(columns [] e data []):
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from matplotlib.colors import LightSource
import numpy as np
from decimal import *
import datetime
#Size
width = 360
height = 240
dpi = 80.0
colors = ['#be1e2d',
'#666699',
'#92d5ea',
'#ee8310',
'#8d10ee',
'#5a3b16',
'#26a4ed',
'#f45a90',
'#e9e744']
#Data
columns = ['2005','2006']
data = [[1.5, 1.5], [1.5,1.5], [1.5,1.5]]
linewidth = 1
N = len(columns)
ind = np.arange(N)
#Re-Size
height_of_group = .9
heightColumn = height_of_group / (len(columns))
fig = plt.figure(1, figsize=(width/dpi,height/dpi),facecolor='w')
ax = fig.add_axes([0.2, 0.3, 0.6, 0.5])
#Draw
tupleRects = ()
idxColor = 0
valPositionCol = ind
for dat in data:
rects = plt.barh(valPositionCol, dat, heightColumn, color=colors[idxColor], alpha=0.8,
linewidth=linewidth)
valPositionCol=valPositionCol+heightColumn
idxColor += 1
if idxColor==9:
idxColor = 0
tupleRects += (rects,)
plt.show()
问题是我有可变数据,我必须找到一个稳定的算法。
答案 0 :(得分:0)
我认为你误解了身高(doc)的含义。单位是轴单位,而不是像素。
heightColumn = height*1.0 / (rdata) / (len(columns))
heightColumn = heightColumn/dpi
到
height_of_group = .9
heightColumn = height_of_group / (len(data))
#heightColumn = heightColumn/dpi
将获得非重叠的条形,只需在组之间留出一些额外的空间。您可以通过使height_of_group
更大或更小来调整组之间的间距,只要它小于1
。