我正在使用
但是,我可以看到右側 x 軸上的數字比左側的數字更緊密地聚集在一起,我想讓它們均勻。
我知道這與這條線有關:
plt.subplots_adjust(wspace=0, top=0.85, bottom=0.1, left=0.2, right=0.8)
我知道如何手動更改(即只更改左右引數)。但是我永遠無法確定我是否準確,因為我只是手動更改這些引數直到它們看起來均勻?
我想知道是否有人可以告訴我如何在不手動更改left和right引數的情況下自動使軸均勻分布?
uj5u.com熱心網友回復:
解決此問題的一種方法是使用set_xlimMatplotlib 中的函式并將其應用于您的子圖。代碼如下所示:
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import seaborn as sns
sns.set()
#%matplotlib notebook
#plt.style.use('classic')
Class = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7']
Lens = [111, 80, 114, 59, 109.0491744186047, 117, 120]
Nums = [124, 28, 22, 41, 85, 33, 156]
data = pd.DataFrame(data=zip(Class,Lens,Nums),columns=['Class','Lens','Nums'])
data.set_index('Class', inplace=True)
font_color = '#525252'
hfont = {'fontname':'Calibri'}
#facecolor = '#eaeaf2'
color_red = '#fd625e'
color_blue = '#01b8aa'
index = data.index
column0 = data['Lens']
column1 = data['Nums']
title0 = "Title 1"
title1 = 'Title 2'
fig, axes = plt.subplots(figsize=(10,5), ncols=2,sharey=True)
fig.tight_layout()
fig.canvas.set_window_title('test') # Adds new title to the window
axes[0].barh(index, column0, align='center', color=color_red, zorder=10)
axes[0].set_title(title0, fontsize=18, pad=15, color=color_red, **hfont)
axes[1].barh(index, column1, align='center', color=color_blue, zorder=10)
axes[1].set_title(title1, fontsize=18, pad=15, color=color_blue, **hfont)
print(column1)
# If you have positive numbers and want to invert the x-axis of the left plot
axes[0].invert_xaxis()
# To show data from highest to lowest
plt.gca().invert_yaxis()
axes[0].grid(False)
axes[1].grid(False)
axes[0].set_facecolor('white')
axes[1].set_facecolor('white')
axes[0].set(yticks=data.index, yticklabels=data.index)
axes[0].yaxis.tick_left()
axes[0].tick_params(axis='y', colors='white') # tick color
#Set xlim
max_columns_value=max([max(column0),max(column1)])
axes[0].set_xlim([max_columns_value,0])
axes[1].set_xlim([0,max_columns_value])
for label in (axes[0].get_xticklabels() axes[0].get_yticklabels()):
label.set(fontsize=13, color=font_color, **hfont)
for label in (axes[1].get_xticklabels() axes[1].get_yticklabels()):
label.set(fontsize=13, color=font_color, **hfont)
plt.subplots_adjust(wspace=0, top=0.85, bottom=0.1, left=0.18, right=0.95)
#axes[0].update_xaxes(showline=True, linewidth=2, linecolor='black')
#plt.update_yaxes(showline=True, linewidth=2, linecolor='black')
plt.show()
輸出給出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/345399.html
標籤:Python matplotlib
