晚上好
hist()matplotlib 在使用 eg或繪制時會改變圖表的縮放比例plot(),這通常很棒。
是否可以在繪圖后凍結子圖中的 x 和 y 軸,以便進一步的繪圖命令不再更改它們?例如:
fig, (plt1, plt2) = plt.subplots(2, 1, figsize=(20, 10))
plt1.hist(…)
plt1.plot(…)
# How can this get done?:
plt1.Freeze X- and Y-Axis
# Those commands no longer changes the x- and y-axis
plt1.plot(…)
plt1.plot(…)
非常感謝,親切的問候,托馬斯
uj5u.com熱心網友回復:
繪制初始圖后使用plt.xlim和plt.ylim獲取當前限制,然后在繪制附加圖后使用這些值設定限制:
import matplotlib.pyplot as plt
# initial data
x = [1, 2, 3, 4, 5]
y = [2, 4, 8, 16, 32]
plt.plot(x, y)
# Save the current limits here
xlims = plt.xlim()
ylims = plt.ylim()
# additional data (will change the limits)
new_x = [-10, 100]
new_y = [2, 2]
plt.plot(new_x, new_y)
# Then set the old limits as the current limits here
plt.xlim(xlims)
plt.ylim(ylims)
plt.show()
輸出圖(請注意 x 軸限制如何 ~[1, 5]即使橙色線在 range 中定義[-10, 100]):

uj5u.com熱心網友回復:
Matplotlib 有一個可以打開或關閉的
uj5u.com熱心網友回復:
要凍結 x 軸,請在繪圖函式上指定域:
import matplotlib.pyplot as plt
fig, (plt1, plt2) = plt.subplots(2, 1, figsize=(20, 10))
# range(min, max, step)
n = range(0, 10, 1) # domain [min, max] = [0, 9]
# make sure your functions has equal length
f = [i * 2 for i in n]
g = [i ** 2 for i in n]
# keep x-axis scale the same by specifying x-axis on the plot function.
plt1.plot(n, f) # funtion (f) range depends on it's value [min, max]
plt1.plot(n, g) # funtion (g) range depends on it's value [min, max]
# range of (f) and (g) impacts the scaling of y-axis
有關 hist 函式引數,請參見matplotlib.pyplot。
uj5u.com熱心網友回復:
@jfaccioni 的答案幾乎是完美的(非常感謝!),但它不適用于 matplotlib 子圖(如要求的那樣),因為不幸的是,Python 經常沒有統一的屬性和方法(即使在同一個模塊中也沒有) ,因此繪圖和子圖的 matplotlib 介面是不同的。在此示例中,此代碼適用于繪圖,但不適用于子圖:
# this works for plots:
xlims = plt.xlim()
# and this must be used for subplots :-(
xlims = plt1.get_xlim()
因此,此代碼適用于子圖:
import matplotlib.pyplot as plt
fig, (plt1, plt2) = plt.subplots(2, 1, figsize=(20, 10))
# initial data
x = [1, 2, 3, 4, 5]
y = [2, 4, 8, 16, 32]
plt1.plot(x, y)
# Save the current limits here
xlims = plt1.get_xlim()
ylims = plt1.get_ylim()
# additional data (will change the limits)
new_x = [-10, 100]
new_y = [2, 2]
plt1.plot(new_x, new_y)
# Then set the old limits as the current limits here
plt1.set_xlim(xlims)
plt1.set_ylim(ylims)
plt.show()
順便說一句:凍結 x 軸和 y 軸甚至可以通過 2 行來完成,因為不幸的是,python 再次具有不一致的屬性:
# Freeze the x- and y axes:
plt1.set_xlim(plt1.get_xlim())
plt1.set_ylim(plt1.get_ylim())
將 xlim 設定為它已經擁有的值根本沒有意義。但是因為 Python matplotlib 濫用了 xlim/ylim 屬性并設定了當前的繪圖大小(而不是限制!),因此此代碼無法按預期作業。
It helps to solve the task in question, but those concepts makes using matplotlib hard and reading matplotlib code is annoying because one must know hidden / unexpected internal behaviors.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424605.html
標籤:Python matplotlib 子情节
上一篇:Seaborn正在繪制一條不同于Matplotlib的線
下一篇:如何使用正確的文本旋轉注釋回歸線
