如何减少python图中不同条形组之间的空间

时间:2021-03-11 01:35:59

标签: python matplotlib bar-chart

我正在尝试绘制组条形图..我使用下面给出的代码绘制此图现在我想要的是减少组条之间的空间,以便压缩图形

图书馆

import numpy as np
import matplotlib.pyplot as plt

# set width of bars
barWidth = 0.1
 
# set heights of bars
a = [3,4, 15, 10, 12]
b = [2,13,4,19,1]
c = [12,3,7,8,4]
d = [12, 13,4,7,14]

 
# Set position of bar on X axis
r1 = np.arange(len(a))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
 
# Make the plot
plt.bar(r1, a,  width=barWidth, edgecolor='white',label='a')
plt.bar(r2, b, width=barWidth, edgecolor='white', label='b') 
plt.bar(r3, c, width=barWidth, edgecolor='white', label='c') 
plt.bar(r4, d, width=barWidth, edgecolor='white', label='d') 
#plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')
 

plt.xticks([r + barWidth for r in range(len(a))], ['A','B', 'C', 'D', 'E'])

plt.yticks(np.arange(0, 20+1, 4))
# Create legend & Show graphic
plt.legend()
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

只需使用 Pandas 数据框。它将使您的代码更加简洁,并会自动为您处理这些问题。

import pandas as pd
import matplotlib.pyplot as plt

a = [3,4, 15, 10, 12]
b = [2,13,4,19,1]
c = [12,3,7,8,4]
d = [12, 13,4,7,14]
df = pd.DataFrame([a,b,c,d], columns=["A", "B", "C", "D", "E"]).transpose()

df.plot(kind = "bar")
plt.legend(["A", "B", "C", "D", "E"])
plt.show()

enter image description here