使用plt.bar柱狀圖減小柱子之間的間隔問題
更新時間:2023年09月14日 16:01:51 作者:Bruce-XIAO
這篇文章主要介紹了使用plt.bar柱狀圖減小柱子之間的間隔問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
plt.bar柱狀圖減小柱子之間的間隔
原始柱狀圖
import matplotlib.pyplot as plt
num_list = [1.5, 0.6, 7.8, 6]
plt.bar(range(len(num_list)), num_list)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import MultipleLocator
taxinyc = {
'gdc':{
'rmse': {
'16': 0.636,
'32': 0.622,
'64': 0.617,
'128': 0.608
},
'mae': {
'16': 0.159,
'32': 0.153,
'64': 0.152,
'128': 0.151
}
},
'scl':{
'rmse': {
'16': 0.604,
'32': 0.608,
'64': 0.607
},
'mae': {
'16': 0.160,
'32': 0.151,
'64': 0.154
}
},
'dcl':{
'rmse': {
'16': 0.612,
'32': 0.608,
'64': 0.610
},
'mae': {
'16': 0.148,
'32': 0.151,
'64': 0.158
}
}
}
taxincd = {
'gdc':{
'rmse': {
'16': 0.322,
'32': 0.322,
'64': 0.321,
'128': 0.320
},
'mae': {
'16': 0.117,
'32': 0.116,
'64': 0.115,
'128': 0.119
}
},
'scl':{
'rmse': {
'16': 0.324,
'32': 0.322,
'64': 0.321
},
'mae': {
'16': 0.128,
'32': 0.116,
'64': 0.118
}
},
'dcl':{
'rmse': {
'16': 0.321,
'32': 0.322,
'64': 0.396
},
'mae': {
'16': 0.116,
'32': 0.116,
'64': 0.222
}
}
}
def plot_data(data,colors):
for i,key1 in enumerate(data.keys()): #[gdc,scl,dcl]
if i == 0:
params = {
'figure.figsize': '4, 4',
'axes.unicode_minus':False
}
xx = [0., 0.7, 1.4, 2.1]
else:
params = {
'figure.figsize': '3, 4',
'axes.unicode_minus': False
}
xx = [0., 0.7, 1.4]
plt.rcParams.update(params)
for key2 in data[key1].keys(): #[rmse,mae']
fig, ax = plt.subplots()
hidden_dims = list(data[key1][key2].keys())
values = list(data[key1][key2].values())
x_center = [index + 0.3 for index in xx]
plt.bar(xx, values, width=0.6, align='edge',color=colors)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
if key2 == 'rmse':
yrange = 0.7
ax.yaxis.set_major_locator(MultipleLocator(0.1))
else:
yrange = 0.18
ax.yaxis.set_major_locator(MultipleLocator(0.03))
plt.ylim(0.,yrange) # y軸取值范圍
plt.ylabel(str.upper(key2))
plt.xticks(x_center, hidden_dims) # 這兒的0.3是配合寬度0.6來的,是他的一半,目的是讓刻度線在柱子的中間
# plt.xlabel("特征", labelpad=8.5)
plt.axis('on') # 增加這行關閉坐標軸顯示,但仍有空白區(qū)域
# plt.margins(0.1) 圖內(nèi)距離坐標軸0.1
plt.subplots_adjust(left=0.2) #整個圖距離畫布左邊距0.2,防止ylabel消失
# 關鍵在于bbox_inches = 'tight',pad_inches = 0,去掉空白區(qū)域
plt.savefig('result/{}_{}.png'.format(key1,key2), bbox_inches='tight', pad_inches=0)
plt.show()
plt.close(fig)
if __name__ == '__main__':
colors = ['#35478C','#4E7AC7','#2FB2F0','#ADD5F7']
plot_data(taxinyc,colors)
# num_list = [1.5, 0.6, 7.8, 6]
# plt.bar(range(len(num_list)), num_list)
# plt.show()效果圖:

折線圖版本
import numpy as np
import matplotlib.pyplot as plt
taxinyc = {
'gdc':{
'rmse': {
'16': 0.636,
'32': 0.622,
'64': 0.617,
'128': 0.608
},
'mae': {
'16': 0.159,
'32': 0.153,
'64': 0.152,
'128': 0.151
}
},
'scl':{
'rmse': {
'16': 0.604,
'32': 0.608,
'64': 0.607
},
'mae': {
'16': 0.160,
'32': 0.151,
'64': 0.154
}
},
'dcl':{
'rmse': {
'16': 0.612,
'32': 0.608,
'64': 0.610
},
'mae': {
'16': 0.148,
'32': 0.151,
'64': 0.158
}
}
}
taxicd = {
'gdc':{
'rmse': {
'16': 0.322,
'32': 0.322,
'64': 0.321,
'128': 0.320
},
'mae': {
'16': 0.117,
'32': 0.116,
'64': 0.115,
'128': 0.119
}
},
'scl':{
'rmse': {
'16': 0.324,
'32': 0.322,
'64': 0.321
},
'mae': {
'16': 0.128,
'32': 0.116,
'64': 0.118
}
},
'dcl':{
'rmse': {
'16': 0.321,
'32': 0.322,
'64': 0.396
},
'mae': {
'16': 0.116,
'32': 0.116,
'64': 0.222
}
}
}
t1=['16','32','64','128']
t2= [16,32,64]
mae = [0.159,0.153,0.152,0.151]
rmse = [0.148,0.151,0.158]
x1 = [0.5,1.0,1.5,2.0]
x2 = [0.5,1.0,1.5]
data = taxicd
figure,ax=plt.subplots(1,3,sharey=True,figsize=(12,4))
index = ['(a)','(b)','(c)']
for i,(idx,key1) in enumerate(zip(index,data.keys())): # [gdc,scl,dcl]
for key2 in ['mae']: # [rmse,mae']
hidden_dims = list(data[key1][key2].keys())
values = list(data[key1][key2].values())
title = idx + 'hidden units of ' + str.upper(key1)
if i == 0:
ax[i].plot(x1, values, 'ro--')
ax[i].set_ylabel(str.upper(key2),fontdict={'fontsize':12})
ax[i].set_xticks(x1)
ax[i].set_xticklabels(hidden_dims,fontdict={'fontsize':12})
else:
ax[i].plot(x2, values, 'ro--')
ax[i].set_xticks(x2)
ax[i].set_xticklabels(hidden_dims,fontdict={'fontsize':12})
ax[i].set_title(title,fontdict={'fontsize':12})
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
plt.savefig('./taxicd_line_graph_hidden_units.png', bbox_inches='tight', pad_inches=0.1)
figure.show()
plt.bar柱狀圖中如何改變每個柱子之間的間距
這是我的柱狀圖,因為之間間距過窄導致數(shù)字擠到了一起,我搜了很多解決間距的方法,但是并沒有針對我這個問題的解決辦法。。。

后來我才發(fā)現(xiàn)其實非常簡單:只用設置figsize的大小就好,figsize大了,間距自然就大了。
import matplotlib.pyplot as plt # 設置figsize的大小 plt.figure(figsize=(15, 5), dpi=80) # 畫柱狀圖,width可以設置柱子的寬度 plt.bar(np.array(x[flag]), np.array(np.sort(y)), width=0.7) # 設置x軸字體的大小 plt.xticks(fontsize=12) plt.show()
效果圖:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python報錯unexpected?indent的解決辦法
這篇文章主要給大家介紹了關于python報錯unexpected?indent的解決辦法,在python中出現(xiàn)"Unexpected indent"可能是代碼的縮進出現(xiàn)問題,需要的朋友可以參考下2023-06-06
使用Pandas將inf, nan轉(zhuǎn)化成特定的值
今天小編就為大家分享一篇使用Pandas將inf, nan轉(zhuǎn)化成特定的值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
一篇文章告訴你如何用Python控制Excel實現(xiàn)自動化辦公
這篇文章主要介紹了教你怎么用Python處理excel實現(xiàn)自動化辦公,文中有非常詳細的代碼示例,對正在學習python的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-08-08
python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法
今天小編就為大家分享一篇python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07

