![](/img/trans.png)
[英]How can I remove space between bars while plotting bar plot using pandas and matplotlib in Python?
[英]how to reduce space between different groups of bars in python plot
我正在嘗試 plot 組條形圖.. i plot 這個圖使用下面給出的代碼現在我想要的是減少組條之間的空間,所以圖表將被壓縮
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()
只需使用 Pandas dataframe。 它將使您的代碼更簡潔,並會自動為您處理這些問題。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.