以下是使用matplotlib(C0和C2是预定义数组)的堆积条代码
N = 1
width = 0.1
ind = [i+1 for i in range(N)]
colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
p = numpy.empty(len(C2), dtype=object)
plt.figure(figsize=(11,11))
prevBar = 0
for index in range(len(C2)):
plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index], label=C0[index])
prevBar = prevBar + C2[index]
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(width/2) for i in ind]
plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')
# set the x ticks with names
plt.xticks(tick_pos, ['All Transactions'])
plt.yticks(np.arange(0,70000,3000))
plt.legend(title="Line" )
plt.show()
结果我得到以下情节。我希望情节更窄,从偏移开始 - 我该怎么做?
答案 0 :(得分:2)
撇开这是否真的是可视化数据的最佳方式的问题,您可以通过将ind = [0]*N
作为x轴,将单个条形图与align='center'
对齐来实现您想要的效果。然后使用plt.xlim(-width*2, width*2)
根据需要填充条形宽度的任意一侧(调整系数2):
import numpy as np
import matplotlib.pyplot as plt
N = 1
C2 = [1400, 5000, 5400, 6000, 12000]
C0 = ['label%d' % (e+1) for e in range(len(C2))]
width = 0.1
ind = [0]*N
colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
p = np.empty(len(C2), dtype=object)
plt.figure(figsize=(11,11))
prevBar = 0
for index in range(len(C2)):
plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index], label=C0[index], align='center')
prevBar = prevBar + C2[index]
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [0]
plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')
# set the x ticks with names
plt.xticks(tick_pos, ['All Transactions'])
plt.yticks(np.arange(0,70000,3000))
plt.legend(title="Line" )
plt.xlim(-width*2, width*2)
plt.show()