![](/img/trans.png)
[英]Pandas and Matplotlib - how can I change plot area to fit in more x-axis text?
[英]How can I change the x axis in matplotlib so there is no white space?
因此,目前正在學習如何在 matplotlib 中導入數據並使用它,即使我有書中的確切代碼,我也遇到了麻煩。
這就是 plot 的樣子,但我的問題是如何在 x 軸的起點和終點之間沒有空白的地方得到它。
這是代碼:
import csv
from matplotlib import pyplot as plt
from datetime import datetime
# Get dates and high temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
#for index, column_header in enumerate(header_row):
#print(index, column_header)
dates, highs = [], []
for row in reader:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
dates.append(current_date)
high = int(row[1])
highs.append(high)
# Plot data.
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates, highs, c='red')
# Format plot.
plt.title("Daily high temperatures, July 2014", fontsize=24)
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
在邊緣設置了一個自動邊距,以確保數據很好地適合軸脊。 在這種情況下,在 y 軸上可能需要這樣的余量。 默認情況下,它以軸跨度為單位設置為0.05
。
要將 x 軸上的邊距設置為0
,請使用
plt.margins(x=0)
或者
ax.margins(x=0)
取決於上下文。 另請參閱文檔。
如果您想擺脫整個腳本中的邊距,您可以使用
plt.rcParams['axes.xmargin'] = 0
在腳本的開頭(當然y
也是如此)。 如果您想完全永久地消除邊距,您可能需要更改matplotlib rc 文件中的相應行:
axes.xmargin : 0
axes.ymargin : 0
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
tips.plot(ax=ax1, title='Default Margin')
tips.plot(ax=ax2, title='Margins: x=0')
ax2.margins(x=0)
或者,使用plt.xlim(..)
或ax.set_xlim(..)
手動設置軸的限制,以便沒有剩余空白。
如果您只想刪除一側而不是另一側的邊距,例如從右側而不是從左側刪除邊距,您可以在 matplotlib 軸對象上使用set_xlim()
。
import seaborn as sns
import matplotlib.pyplot as plt
import math
max_x_value = 100
x_values = [i for i in range (1, max_x_value + 1)]
y_values = [math.log(i) for i in x_values]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
sn.lineplot(ax=ax1, x=x_values, y=y_values)
sn.lineplot(ax=ax2, x=x_values, y=y_values)
ax2.set_xlim(-5, max_x_value) # tune the -5 to your needs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.