[英]matplotlib bar chart: space out bars
我如何使用 matplotlib 條形圖增加每個條形圖之間的空間,因為它們一直將它們自己塞到中心。 (這是它目前的樣子)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def ww(self):#wrongwords text file
with open("wrongWords.txt") as file:
array1 = []
array2 = []
for element in file:
array1.append(element)
x=array1[0]
s = x.replace(')(', '),(') #removes the quote marks from csv file
print(s)
my_list = ast.literal_eval(s)
print(my_list)
my_dict = {}
for item in my_list:
my_dict[item[2]] = my_dict.get(item[2], 0) + 1
plt.bar(range(len(my_dict)), my_dict.values(), align='center')
plt.xticks(range(len(my_dict)), my_dict.keys())
plt.show()
嘗試更換
plt.bar(range(len(my_dict)), my_dict.values(), align='center')
與
plt.figure(figsize=(20, 3)) # width:20, height:3
plt.bar(range(len(my_dict)), my_dict.values(), align='edge', width=0.3)
有兩種方法可以增加條形之間的空間供參考這里是繪圖功能
plt.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
plot 函數有一個寬度參數來控制條的寬度。 如果減小寬度,條形之間的空間將自動減小。 默認情況下,您的寬度設置為 0.8。
width = 0.5
如果要保持寬度不變,則必須將條形圖放置在 x 軸上的位置隔開。 您可以使用任何縮放參數。 例如
x = (range(len(my_dict)))
new_x = [2*i for i in x]
# you might have to increase the size of the figure
plt.figure(figsize=(20, 3)) # width:10, height:8
plt.bar(new_x, my_dict.values(), align='center', width=0.8)
此答案會更改條形之間的空間,並且還會在 x 軸上旋轉標簽。 它還允許您更改圖形大小。
fig, ax = plt.subplots(figsize=(20,20))
# The first parameter would be the x value,
# by editing the delta between the x-values
# you change the space between bars
plt.bar([i*2 for i in range(100)], y_values)
# The first parameter is the same as above,
# but the second parameter are the actual
# texts you wanna display
plt.xticks([i*2 for i in range(100)], labels)
for tick in ax.get_xticklabels():
tick.set_rotation(90)
將 x 軸限制從稍微負值開始設置為比圖中的條數略大的值,並在 barplot 命令中更改條的寬度
例如,我為只有兩個條形圖的條形圖做了這個
ax1.axes.set_xlim(-0.5,1.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.